I have a JTextField in a swing application that should accept only numbers and commas. I have handled this using the following code.
String lstAllowedCharsForSlotList=new String(new char[]{'1','2','3','4','5','6','7','8','9','0','\b','\t',','});
@Override
public void keyPressed(KeyEvent e) {
if(lstAllowedCharsForSlotList.indexOf(e.getKeyChar())==-1)
e.consume();
}
@Override
public void keyReleased(KeyEvent e) {
if(lstAllowedCharsForSlotList.indexOf(e.getKeyChar())==-1)
e.consume();
}
@Override
public void keyTyped(KeyEvent e) {
if(lstAllowedCharsForSlotList.indexOf(e.getKeyChar())==-1)
e.consume();
}
The problems with this are:
- duplication of code in event processing
- does not allow the user to navigate in textfield by using arrow keys, home, end
- the user cannot use any other keys like delete,insert
Can anyone help with a better solution?