如何验证JTextField? [英] How to validate a JTextField?
问题描述
如何验证文本字段在Swing小数点后只输入4位数?
How to validate a textfield to enter only 4 digits after the decimal point in Swing?
推荐答案
Swing中的任何验证都可以使用 InputVerifier执行
。
Any validation in Swing can be performed using an InputVerifier
.
1。首先创建自己的输入验证器:
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。然后将该类的实例分配给文本字段。 (实际上任何 JComponent
都可以验证)
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.
另请参阅SDK文档: JComponent #setInputVerifier 。
Also have a look at the SDK documentation: JComponent#setInputVerifier.
这篇关于如何验证JTextField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!