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

前端 未结 19 1880
陌清茗
陌清茗 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 simple approach is to subclass JTextField and override createDefaultModel() by returning customised PlainDocument subclass. Example - a textfield for integers only:

    public class NumberField extends JTextField {
    
    
    @Override
    protected Document createDefaultModel() {
        return new Numberdocument();
    }
    
    class Numberdocument extends PlainDocument
    {
        String numbers="1234567890-";
        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {
            if(!numbers.contains(str));
            else    super.insertString(offs, str, a);
        }
    }
    

    Process input in insertString() any way.

    0 讨论(0)
  • 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.
        }
      }
    };
    
    0 讨论(0)
  • 2020-11-22 04:09

    Look at JFormattedTextField.

    0 讨论(0)
  • 2020-11-22 04:12

    You can create a beautiful text field in java that accepts or allows only numeric values.. You can even set the precision for the float values... check the code in zybocodes

    0 讨论(0)
  • 2020-11-22 04:14

    numberField = new JFormattedTextField(NumberFormat.getInstance());

    Formatted text field tutorial

    0 讨论(0)
  • 2020-11-22 04:15

    I think it is the best solution:

    JTextField textField = new JFormattedTextField(new MaskFormatter("###")); //
    
    0 讨论(0)
提交回复
热议问题