Hunter
Hunter

Reputation: 53

How to know if the JTextField is empty?

I am building a GUI for some Java project. I need to validate what user input on JTextField. But I have a small problem.

The JTextField is for entering Integer. So, I did try and catch for NumberFormatException. The question is: if the user fires an action (press Enter) without writing anything in the JTextField even space, How could I handle this?

int id = 0;
try {
id = Integer.parseInt(tfID.getText());
} catch (NumberFormatException e1 ) {
    if (tfID.getText()==null) //This does not work
        idError.setText("Enter an Integer");
    else
        idError.setText("Intgers only accepted");
}               

I want to show a message on another JTextfield (which is idError in this case) to tell the user to enter an Integer.

Thanks in advance.

Upvotes: 0

Views: 58

Answers (1)

Hunter
Hunter

Reputation: 53

Instead of using:

if (tfID.getText()==null)

use:

if( tfID.getText().equals("") )

which will return true if and only if the two strings are equal, which is here tfID.getText() and ("").

Thanks for you all.

Upvotes: 3

Related Questions