Below is the KeyAdapter I tried to get working to only accept values less than 65535. It seems as though it gets it one keystroke behind where it actually should. For example, If I type "55", the System.out.println will yield "5", doing "3298" will yield "329", etc.
// 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();
}
}
}
};