0

I am trying to create a JTextfield that only accepts integers. But for some reason the keycode is not being sent to the application

private void keyTyped(java.awt.event.KeyEvent evt) {                                   
    String s = String.valueOf(evt.getKeyChar());
    try{
        if(!(s.matches("[0-9]+")))
    {
        evt.setKeyCode(KeyEvent.VK_DELETE);
    }
    }catch(Exception e){}
}                                  
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Syed Sami
  • 19
  • 1
  • 3

1 Answers1

1

Your problem is one of approach -- you shouldn't be using a KeyListener with a Swing text component. Instead if you want to filter keyboard input correctly with text components such as a JTextField, add a DocumentFilter to the JTextField's Document. In the filter, override the 3 methods that it contains -- insertString(...), remove(...), and replace(...) -- and only call the super's method if the current text plus the additional text (or minus the deleted text) is valid.

For a complete example (by me), please look at this answer of mine to a similar question.

Another easier option is to use an InputVerifier.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373