I want to determine if JTextField.getText()
contains only numbers between 0-9, where anything else is not accepted such as letters and other characters. What's a good way to do this? thanks.
Asked
Active
Viewed 133 times
-3

user2052855
- 23
- 1
- 2
- 5
-
With `JTextField.getText().matches("\\d+");` – AntonH Apr 10 '14 at 21:11
-
Parse it and catch the possible exception. Shouldn't be too expensive considering it requires user input (and thus won't be likely to be done thousands of times in a row). – Jeroen Vannevel Apr 10 '14 at 21:12
-
1Or just use `StringUtils.isNumeric()` – azurefrog Apr 10 '14 at 21:14
-
possible duplicate of [What's the best way to check to see if a String represents an integer in Java?](http://stackoverflow.com/questions/237159/whats-the-best-way-to-check-to-see-if-a-string-represents-an-integer-in-java) – pennstatephil Apr 10 '14 at 21:14
-
int value(S), plural? so "123 456 789" would be ok? e.g. ints separated by spaces? – Marc B Apr 10 '14 at 21:15
-
@MarcB he did say "other characters" for unacceptable characters, so I'd assume space is out. – pennstatephil Apr 10 '14 at 21:16
-
@pennstatephil: yeah,but also says valueS, implying there may be more than one. – Marc B Apr 10 '14 at 21:16
-
@MarcB, ah, I read that as more than one character, that is "123" contains only int values. could be a typo, too. – pennstatephil Apr 10 '14 at 21:18
-
yeah, could go either way. multiple individual "int" values, e.g "123", being "three ints", but one single value – Marc B Apr 10 '14 at 21:20
-
Use a `JSpinner` instead. – Andrew Thompson Apr 11 '14 at 01:28
1 Answers
1
If you are using NetBeans to build your GUI, you just need to put regular JTextFields in your GUI and in the creation code, you will specify the constructor of IntegerField.
OR
Use JFormattedTextField capabilities.
numberField = new JFormattedTextField(NumberFormat.getInstance());
.
Have a look at example(http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html).

Arjun Chaudhary
- 2,373
- 2
- 19
- 36