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
The object of a JTextField class is a text component that allows the editing of a single line text.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With