How to validate a JTextField?

前端 未结 2 1807
后悔当初
后悔当初 2020-11-28 15:04

How to validate a textfield to enter only 4 digits after the decimal point in Swing?

2条回答
  •  失恋的感觉
    2020-11-28 15:32

    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:

    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.

提交回复
热议问题