Search code examples
javaswingnetbeansjframejtextfield

How to intercept keyboard strokes going to Java Swing JTextField?


The JTextField is a calculator display initialized to zero and it is bad form to display a decimal number with a leading 0 like 0123 or 00123. The numeric buttons (0..9) in a NetBeans Swing JFrame use append() [below] to drop the leading zeros, but the user may prefer the keyboard to a mouse, and non-numeric characters also need to be handled.

private void append(String s) {
    if (newEntry) {
        newEntry = false;
        calcDisplay.setText(s);
    } else if (0 != Float.parseFloat(calcDisplay.getText().toString())) {
        calcDisplay.setText(calcDisplay.getText().toString() + s);
    }
}

Solution

  • You could restrict the characters input to the JTextField by adding a custom KeyListener. Here is a quick example to demonstrate the idea:

    myTextField.addKeyListener(new KeyAdapter() {
      @Override
      public void keyTyped(KeyEvent e) {
        char c = e.getKeyChar();
        if (!Character.isDigit(c)) {
          e.consume(); // Stop the event from propagating.
        }
      }
    });
    

    Of course, you need to consider special keys like Delete and combinations like CTRL-C, so your KeyListener should be more sophisticated. There are probably even freely available utilities to do most of the grunt work for you.