What is a simple way to create a text field (or such) that only allows the user to enter ints/doubles in Java?

后端 未结 3 1458
别跟我提以往
别跟我提以往 2020-12-21 14:01

I am looking for a way to ensure that my text field (JTextField, JFormattedTextField) is returning a double or int rather than a string when I call .getText(). What is the b

相关标签:
3条回答
  • 2020-12-21 14:33
    1. Register InputVerifier and call method getValue from JFormattedTextField

      public class FormattedTextFieldVerifier extends InputVerifier {
          public boolean verify(JComponent input) {
           if (input instanceof JFormattedTextField) {
               JFormattedTextField ftf = (JFormattedTextField)input;
               AbstractFormatter formatter = ftf.getFormatter();
               if (formatter != null) {
                   String text = ftf.getText();
                   try {
                        formatter.stringToValue(text);
                        return true;
                    } catch (ParseException pe) {
                        return false;
                    }
                }
            }
            return true;
        }
        public boolean shouldYieldFocus(JComponent input) {
            return verify(input);
        }
      

      }

    0 讨论(0)
  • 2020-12-21 14:45

    Use JFormattedTextField.

    0 讨论(0)
  • 2020-12-21 14:47

    I would check the input in the textbox callback and simply make the box red or create an alert message nearby. You can remove the non-numeric character from the textbox string.

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