Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore the key press event in Swing?

I want to make the text field only accept numeric and backspace button from the user.

I have added the function that use to check the keycode from the user, but I don't know how to stop the key press event if the keycode is not numeric.

What code do I need to add into the function to stop the event??

 private void jTextField2KeyPressed(java.awt.event.KeyEvent evt)   
 {                                       

   if(!((evt.getKeyCode()==8) || (evt.getKeyCode()>48 && evt.getKeyCode()<57)))
   {
      //how to stop the key pressed event
   }
 }
like image 532
e-qi Avatar asked Dec 04 '22 19:12

e-qi


1 Answers

You don't need to mess with the Swing event handling to achieve this.

The best way is to use a JFormattedTextField instead.

See the Java tutorial for details:

http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

like image 152
a_horse_with_no_name Avatar answered Dec 20 '22 18:12

a_horse_with_no_name