Is there any way to accept only numeric values in a JTextField?

前端 未结 19 1884
陌清茗
陌清茗 2020-11-22 03:10

Is there any way to accept only numeric values in a JTextField? Is there any special method for this?

19条回答
  •  醉话见心
    2020-11-22 04:07

    A quick solution:

    JTextField textField = new JTextField() {
      public void processKeyEvent(KeyEvent ev) {
        char c = ev.getKeyChar();
        if (c >= 48 && c <= 57) { // c = '0' ... c = '9'
          super.processKeyEvent(ev);
        }
      }
    };
    

    The problem with the above solution is that the user cannot use the Delete, Left Arrow, Right Arrow, or Backspace keys in the text field, so I suggest using this solution:

    this.portTextField = new JTextField() {
      public void processKeyEvent(KeyEvent ev) {
        char c = ev.getKeyChar();
        try {
          // Ignore all non-printable characters. Just check the printable ones.
          if (c > 31 && c < 127) {
            Integer.parseInt(c + "");
          }
          super.processKeyEvent(ev);
        }
        catch (NumberFormatException nfe) {
          // Do nothing. Character inputted is not a number, so ignore it.
        }
      }
    };
    

提交回复
热议问题