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();
}
}
}
};
So, instead of a
KeyListener
, which you've found, is unreliable and will cause lots of nasty side effects (and possible Document Mutation exceptions :P), we should use aDocumentFilter
, cause that's what it's designed forYou will need to apply this to the field's document
I'd check out
For some more info
UPDATE for Decimal inclusion
Basically, if you want to allow the inclusion of a decimal, you need to allow for the character in the
valid
method.You also need to check the current document's contents