0

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?

Prasanna
  • 187
  • 1
  • 10
  • 2
    Try using `JFormattedTextField`, similar questions are already answered on SO, http://stackoverflow.com/questions/1313390/is-there-any-way-to-accept-only-numeric-values-in-a-jtextfield, http://stackoverflow.com/questions/18084104/accept-only-numbers-and-a-dot-in-java-textfield and http://stackoverflow.com/questions/11093326/restricting-jtextfield-input-to-integers – Shrikant Havale Apr 01 '15 at 09:49
  • Could the JFormattedTextField enable me to use custom formats? The format in my case is comma & numbers. Also the user should not be allowed to key in any other visible character – Prasanna Apr 01 '15 at 10:22
  • can you check this link of custom format for allowing numbers from 1-1000, http://www.java-tips.org/java-se-tips/javax.swing.text/how-to-make-custom-input-text-formatter-in.html, normally it is not a good idea to post links as they might get broken in long run, but as this question is marked as duplicate, I cannot answer it with the example from link. – Shrikant Havale Apr 01 '15 at 11:08

0 Answers0