views:

52

answers:

2

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);
    }
}
+3  A: 

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.

maerics
Big help. Thank you very much.
JackN
The DocumentFilter suggestion is the way to go. This was added to Swing in JDK4 and is the preferred approach over using KeyEvents. Your comment about CTRL-C is one of the reasons a filter is better.
camickr
Thanks. I'll take a look.
JackN
+3  A: 

You can do this with DocumentFilter.

Here's a simple complete example program.

Tom Hawtin - tackline
Tom. The link is a bit hard to read as one long unformatted line.
JackN
Trying to read it as a Windows text file? I think WordPad should handle it, but Notepad will not. Chrome on Windows shows it correctly; IE does not. I would link to the weblog entry which describes it, but I can't find that in google (probably jroller being flaky).
Tom Hawtin - tackline