How to validate a JTextField?

前端 未结 2 1797
后悔当初
后悔当初 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.

    0 讨论(0)
  • 2020-11-28 15:36

    Any validation in Swing can be performed using an InputVerifier.

    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. 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.

    Also have a look at the SDK documentation: JComponent#setInputVerifier.

    0 讨论(0)
提交回复
热议问题