Any validation in Swing can be performed using an InputVerifier
.
1. First create your own input verifier:
public class MyInputVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
try {
BigDecimal value = new BigDecimal(text);
return (value.scale() <= Math.abs(4));
} catch (NumberFormatException e) {
return false;
}
}
}
2. Then assign an instance of that class to your text field. (In fact any JComponent
can be verified)
myTextField.setInputVerifier(new MyInputVerifier());
Of course you can also use an anonymous inner class, but if the validator is to be used on other components, too, a normal class is better.
Also have a look at the SDK documentation: JComponent#setInputVerifier.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…