如何截取进入Java Swing JTextField的键盘笔触? [英] How to intercept keyboard strokes going to Java Swing JTextField?
问题描述
JTextField是一个计算器显示,被初始化为零,并且以十进制数字形式显示以0或00123等开头的十进制数字是一种不好的形式.NetBeansSwing JFrame中的数字按钮(0..9)使用append()[下方]来删除前导零,但用户可能更喜欢键盘而不是鼠标,并且还需要处理非数字字符.
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);
}
}
推荐答案
您可以通过添加自定义KeyListener来限制输入到JTextField的字符.这是一个简单的例子来说明这个想法:
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.
}
}
});
当然,您需要考虑特殊键(如Delete)和组合键(如CTRL-C),因此KeyListener应该更复杂.甚至可能有免费的实用程序可以为您完成大多数繁琐的工作.
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.
这篇关于如何截取进入Java Swing JTextField的键盘笔触?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!