Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a JTextField is a number

quick question: I have a JTextField for user input, in my focus listener, when the JTextField loses focus, how can I check that the data in the JTextField is a number? thanks

like image 599
Beef Avatar asked Aug 01 '11 03:08

Beef


People also ask

What is the type of text in a JTextField object?

The object of a JTextField class is a text component that allows the editing of a single line text.

What is the difference between JTextField and JTextArea?

The main difference between JTextField and JTextArea in Java is that a JTextField allows entering a single line of text in a GUI application while the JTextArea allows entering multiple lines of text in a GUI application.

Is JTextField a class?

The class JTextField is a component that allows editing of a single line of text. JTextField inherits the JTextComponent class and uses the interface SwingConstants. The constructor of the class are : JTextField() : constructor that creates a new TextField.


2 Answers

Try performing Integer.parseInt(yourString) and if it throws a NumberFormatException you'll know the string isn't a valid integer

try {
     Integer.parseInt(myString);
     System.out.println("An integer"):
}
catch (NumberFormatException e) {
     //Not an integer
}

Another alternative is Regex:

boolean isInteger = Pattern.matches("^\d*$", myString);
like image 114
Oscar Gomez Avatar answered Sep 30 '22 17:09

Oscar Gomez


See How to Use Formatted Text Fields.

If you don't want to use a formatted text field then you should be using an InputVerifier, not a FocusListener.

You can also use a DocumentFilter to filter text as it is typed.

like image 32
camickr Avatar answered Sep 30 '22 17:09

camickr