Disable input some symbols to JTextField

前端 未结 7 790
长发绾君心
长发绾君心 2020-12-05 21:07

How can I disable input of any symbol except digits to JTextField?

7条回答
  •  失恋的感觉
    2020-12-05 22:02

    Option 1) change your JTextField with a JFormattedTextField, like this:

    try {
       MaskFormatter mascara = new MaskFormatter("##.##");
       JFormattedTextField textField = new JFormattedTextField(mascara);
       textField.setValue(new Float("12.34"));
    } catch (Exception e) {
       ...
    }
    

    Option 2) capture user's input from keyboard, like this:

    JTextField textField = new JTextField(10);
    textField.addKeyListener(new KeyAdapter() {
       public void keyTyped(KeyEvent e) {
          char c = e.getKeyChar();
          if ( ((c < '0') || (c > '9')) && (c != KeyEvent.VK_BACK_SPACE)) {
             e.consume();  // ignore event
          }
       }
    });
    

提交回复
热议问题