jacknad
jacknad

Reputation: 13739

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);
    }
}

Upvotes: 1

Views: 2509

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

You can do this with DocumentFilter.

(Edit: This answer originally included a ling to a simple complete example program on my now defunct weblog.)

Upvotes: 3

maerics
maerics

Reputation: 156424

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.

Upvotes: 6

Related Questions