将JTextField输入限制为整数我知道这个问题已经问过无数次了,但我还是找不到一个简单的解决办法。我有一个JTextField,它只接受正整数作为输入。我需要一种方法来确保这里没有其他的输入。我已经有一个keyListener附加到这个控件。删除此侦听器要处理的其他代码,我有以下内容: txtAnswer.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
/* Restrict input to only integers */
if (key < 96 && key > 105) e.setKeyChar('');
};
});如您所见,我正在尝试使用键码来检查刚才按下的键是否在整数范围内。这似乎很管用。但我想做的是,如果条目超出了这个范围,就忽略它。密码e.setKeyChar('')本来是用来处理这事的,但不起作用。代码将编译,但没有可见的效果。有人能告诉我是否在正确的轨道上吗?我能替换什么e.setKeyChar('')让这件事成功吗?还是我完全走错了方向?谢谢。
3 回答
胡说叔叔
TA贡献1804条经验 获得超8个赞
JFormattedTextField
public static void main(String[] args) { NumberFormat format = NumberFormat.getInstance(); NumberFormatter formatter = new NumberFormatter(format); formatter.setValueClass(Integer.class); formatter.setMinimum(0); formatter.setMaximum(Integer.MAX_VALUE); formatter.setAllowsInvalid(false); // If you want the value to be committed on each keystroke instead of focus lost formatter.setCommitsOnValidEdit(true); JFormattedTextField field = new JFormattedTextField(formatter); JOptionPane.showMessageDialog(null, field); // getValue() always returns something valid System.out.println(field.getValue());}
添加回答
举报
0/150
提交
取消