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

喜你入骨 提交于 2019-11-28 10:36:35

问题


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


回答1:


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

    }




回答2:


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.




回答3:


Use JFormattedTextField.



来源:https://stackoverflow.com/questions/2510047/what-is-a-simple-way-to-create-a-text-field-or-such-that-only-allows-the-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!