Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何验证JTextField?_Java_Swing - Fatal编程技术网

Java 如何验证JTextField?

Java 如何验证JTextField?,java,swing,Java,Swing,如何验证文本字段以仅在Swing中的小数点后输入4位数字?Swing中的任何验证都可以使用 一,。首先创建您自己的输入验证程序: public class MyInputVerifier extends InputVerifier { @Override public boolean verify(JComponent input) { String text = ((JTextField) input).getText(); try {

如何验证文本字段以仅在Swing中的小数点后输入4位数字?

Swing中的任何验证都可以使用

一,。首先创建您自己的输入验证程序:

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;
        }
    }
}
当然,您也可以使用匿名内部类,但是如果验证器也要用于其他组件,则使用普通类更好


还可以查看SDK文档:。

您可以使用
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);
    }
  }
}
只要文本字段不包含有效的输入,错误消息就会如下图所示

验证输入后,错误消息将不可见

当然,您可以根据需要替换验证操作。例如,如果输入无效,您可能希望在单击按钮时显示一些弹出窗口,等等


我把这些放在一起是为了展示一个替代已经给出的答案。在某些情况下,此解决方案可能更合适。在某些情况下,给出的答案可能更合适。但有一点是肯定的,替代方法总是一件好事。

使用
BigDecimal
,然后使用
scale()
检查小数位数。感谢大家提供的提示和代码片段。如果发生断开连接的情况,我将尝试告诉您可能添加的方法是何时触发此验证方法,以及如何从JComponent获取结果
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);
    }
  }
}