如何禁止输入除数字以外的任何符号到 JTextField
?
最佳答案
选项 1) 将 JTextField 更改为 JFormattedTextField,如下所示:
try {
MaskFormatter mascara = new MaskFormatter("##.##");
JFormattedTextField textField = new JFormattedTextField(mascara);
textField.setValue(new Float("12.34"));
} catch (Exception e) {
...
}
选项 2)从键盘捕获用户的输入,如下所示:
JTextField textField = new JTextField(10);
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if ( ((c < '0') || (c > '9')) && (c != KeyEvent.VK_BACK_SPACE)) {
e.consume(); // ignore event
}
}
});
关于java - 禁止向 JTextField 输入一些符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4863850/