Java 如何验证 JTextField?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2749521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate a JTextField?
提问by Chandu
How to validate a textfield to enter only 4 digits after the decimal point in Swing?
如何验证文本字段以在 Swing 中仅输入小数点后 4 位数字?
采纳答案by Daniel Rikowski
Any validation in Swing can be performed using an InputVerifier
.
Swing 中的任何验证都可以使用InputVerifier
.
1. First create your own input verifier:
1.首先创建自己的输入验证器:
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)
2. 然后将该类的一个实例分配给您的文本字段。(实际上任何JComponent
都可以验证)
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.
另请查看 SDK 文档:JComponent#setInputVerifier。
回答by hfontanez
You could probably accomplish the same with DocumentListener
. All you have to do is validate the input string against the desired string pattern. In this case, the pattern seems to be one or more digits, followed by a period, AND exactly 4 digits after the decimal point. The code below demonstrates using DocumentListener
to accomplish this:
您可能可以使用DocumentListener
. 您所要做的就是根据所需的字符串模式验证输入字符串。在这种情况下,模式似乎是一位或多位数字,后跟一个句点,以及小数点后的 4 位数字。下面的代码演示了如何使用它DocumentListener
来完成此操作:
public class Dummy
{
private static JTextField field = new JTextField(10);
private static JLabel errorMsg = new JLabel("Invalid input");
private static String pattern = "\d+\.\d{4}";
private static JFrame frame = new JFrame();
private static JPanel panel = new JPanel();
public static void main(String[] args)
{
errorMsg.setForeground(Color.RED);
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 0, 0, 5);
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.SOUTH;
panel.add(errorMsg, c);
c.gridx = 1;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
panel.add(field, c);
frame.getContentPane().add(panel);
field.getDocument().addDocumentListener(new DocumentListener()
{
@Override
public void removeUpdate(DocumentEvent e)
{
validateInput();
}
@Override
public void insertUpdate(DocumentEvent e)
{
validateInput();
}
@Override
public void changedUpdate(DocumentEvent e) {} // Not needed for plain-text fields
});
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static void validateInput()
{
String text = field.getText();
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
if (m.matches())
{
errorMsg.setForeground(frame.getBackground());
}
else
{
errorMsg.setForeground(Color.RED);
}
}
}
As long as the text field does not contain a valid input, the error message is shown like the image below.
只要文本字段不包含有效输入,错误消息就会显示如下图。
Once the input is validated, the error message will not be visible.
一旦输入被验证,错误消息将不可见。
Of course, you can replace the validation action to whatever you need. For example, you may want to display some popup when a button is clicked if the input is not valid, etc.
当然,您可以将验证操作替换为您需要的任何操作。例如,如果输入无效,您可能希望在单击按钮时显示一些弹出窗口等。
I threw this together to show an alternative to answer given already. There might be cases when this solution might be more suitable. There might be cases when the given answer might be more suitable. But one thing is certain, alternatives are always a good thing.
我把它放在一起以显示已经给出的答案的替代方案。在某些情况下,此解决方案可能更合适。在某些情况下,给出的答案可能更合适。但有一件事是肯定的,替代品总是一件好事。