Just a quick question, How do i ensure my JtextField only accepts numeric values? I want it to to diplsy an error message if the user entered anything else thank you
Asked
Active
Viewed 2,111 times
1
-
3See also http://stackoverflow.com/questions/1313390/is-there-any-way-to-accept-only-numeric-values-in-a-jtextfield/1313448#1313448 - no need for nasty error messasges. – Tom Hawtin - tackline Dec 14 '10 at 17:26
-
Try this: http://stackoverflow.com/questions/1313390/is-there-any-way-to-accept-only-numeric-values-in-a-jtextfield – Igor Dec 14 '10 at 17:17
4 Answers
6
You can use a JFormattedTextField
. Construct it using a NumberFormatter
and it will only accept numbers.
The JFormattedTextField
has a bunch of configurable options that let you decide how bad input is handled. I recommend looking at the documentation.

jjnguy
- 136,852
- 53
- 295
- 323
1
You can either add a key event listener and check each char typed in or there are document formatters (NumberFormatter) you can install that will not allow you to enter anything but a number.

Merky
- 494
- 2
- 4
0
Associate a key listener with the text field and check for the value just inserted. If value inserted is not an integer, then prompt error.

Logan
- 2,445
- 4
- 36
- 56
-
I like this idea but but how would i check for value entered? might you have an example code? thanks – Maxi90 Dec 14 '10 at 17:50
-1
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("");
}
}

Pranjal Choladhara
- 845
- 2
- 14
- 35
-
keyListeners are too low-level for such a task, they are not safe enough: it'll miss pasted texted. – kleopatra Sep 28 '13 at 15:30