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
You can use JFormattedTextField . Build it using NumberFormatter and it will only accept numbers.
JFormattedTextField
NumberFormatter
JFormattedTextField has a set of custom parameters that let you decide how bad information is handled. I recommend looking at the documentation.
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.
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.
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(""); } }