2

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 best way to do this (if possible)?

Thanks!

badPanda :D

badpanda
  • 2,446
  • 5
  • 34
  • 45

3 Answers3

3
  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);
      }
    

    }

uthark
  • 5,333
  • 2
  • 43
  • 59
1

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.

Holograham
  • 1,348
  • 1
  • 13
  • 34
1

Use JFormattedTextField.

Roman
  • 64,384
  • 92
  • 238
  • 332