Java JTextfields

Just a quick question, How to ensure that JtextField accepts only numeric values? I want it to give an error message if the user entered anything else thanks

+1
java swing jtextfield
source share
4 answers

You can use JFormattedTextField . Build it using NumberFormatter and it will only accept numbers.

JFormattedTextField has a set of custom parameters that let you decide how bad information is handled. I recommend looking at the documentation.

+6
source share

You can either add a key event listener and check each char entered, or create document formatters (NumberFormatter) that you can set, which will not allow you to enter anything but a number.

+1
source share

Associate a key listener with a text box and check the value just inserted. If the inserted value is not an integer, then an error message is displayed.

0
source share

I use this trick.

 private void myTextFieldKeyReleased(java.awt.event.KeyEvent evt) { try{ int i = Integer.parseInt(myTextField.getText()); } catch(Exception ex){ //Show error message here with JOptionPane.showMessageDialog(null, "Invalid Input...!"); myTexTField.setText(""); } } 
-one
source share

All Articles