下面是我试图开始工作以仅接受小于 65535 的值的 KeyAdapter。似乎它在实际应该的位置后面敲击了一个键。例如,如果我输入“55”,System.out.println 将产生“5”,执行“3298”将产生“329”,等等。
// Allows for unsigned short values only
KeyAdapter unsignedShortAdapter = new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
int tempInt = 0;
JTextField temp = null;
if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
getToolkit().beep();
e.consume();
}
try {
temp = (JTextField) e.getSource();
System.out.println(temp.getText());
tempInt = (Integer.parseInt(temp.getText().toString()));
} catch (NumberFormatException e1) {
} finally {
if (tempInt > (Short.MAX_VALUE * 2)) {
getToolkit().beep();
e.consume();
temp.setText(temp.getText().substring(0, temp.getText().length() - 1));
invalidate();
}
}
}
};