如何validationJTextField?

如何validation文本字段在Swing小数点后只输入4位数?

可以使用InputVerifier执行Swing中的任何validation。

1.首先创建自己的输入validation器:

 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都可以validation)

 myTextField.setInputVerifier(new MyInputVerifier()); 

当然,您也可以使用匿名内部类,但如果validation器也要用于其他组件,则普通类更好。

另请参阅SDK文档: JComponent #setInputVerifier 。

您可以使用DocumentListener完成相同的操作。 您所要做的就是根据所需的字符串模式validation输入字符串。 在这种情况下,模式似乎是一个或多个数字,后跟一个句点,和小数点后面的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); } } } 

只要文本字段不包含有效输入,就会显示错误消息,如下图所示。

输入无效

validation输入后,将不会显示错误消息。

有效的输入

当然,您可以将validation操作替换为您需要的任何操作。 例如,如果输入无效,您可能希望在单击按钮时显示一些弹出窗口等。

我把它扔在一起,以显示已经给出的答案的替代方案。 可能存在此解决方案可能更合适的情况。 可能存在给定答案可能更合适的情况。 但有一点可以肯定,替代方案总是好事。