How to intercept keyboard strokes going to Java Swing JTextField?

随声附和 提交于 2019-12-13 02:30:28

问题


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

回答1:


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.




回答2:


You can do this with DocumentFilter.

Here's a simple complete example program.



来源:https://stackoverflow.com/questions/3622402/how-to-intercept-keyboard-strokes-going-to-java-swing-jtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!