Disable input some symbols to JTextField

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

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

相关标签:
7条回答
  • 2020-12-05 21:44

    For a better user experience

    Others have mentioned the use of JFormattedTextField or KeyListeners to prevent invalid data from being entered but from a usability point of view I find it very annoying to start typing into a field and nothing happens.

    To provide a better user experience you can allow the user to enter non-numeric values in the field but use a validator to provide feedback to the user and disable the submit button.

    0 讨论(0)
  • 2020-12-05 21:47

    You can add a custom KeyListener that intercepts key strokes and doesn't propogate invalid key strokes to the JTextField.

    0 讨论(0)
  • 2020-12-05 21:51

    How to Use Formatted Text Fields

     amountField = new JFormattedTextField(NumberFormat.getIntegerInstance());
    

    You can also create your own format to customize.

    0 讨论(0)
  • 2020-12-05 21:55

    The answer is JFormattedTextField. See my answer on this duplicate question:

    You can use a JFormattedTextField. Construct it using a NumberFormatter and it will only accept numbers.

    The JFormattedTextField has a bunch of configurable options that let you decide how bad input is handled. I recommend looking at the documentation.

    0 讨论(0)
  • 2020-12-05 21:55

    Just consume all chars that is not a digit like this:

    public static void main(String[] args) {
        JFrame frame = new JFrame("Test");
    
        frame.add(new JTextField() {{
            addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e) {
                    if (!Character.isDigit(e.getKeyChar()))
                        e.consume();
                }
            });
        }});
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setVisible(true);
    }
    
    0 讨论(0)
  • 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
          }
       }
    });
    
    0 讨论(0)
提交回复
热议问题