Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What value is returned by empty JTextField?

Status
Not open for further replies.

rdg2cig

Programmer
Sep 16, 1999
22
0
0
US
I would like check to see if the user entered any value in a JTextField before clicking a JButton in order determine the branch to take in a conditional statement. In the JButton actionPerformed() method I have a statement such as:

if(JTextField1.getText() == null){
... do something ...
}
else{
... do something else ...
}

My problem is that 'null' does not appear to be returned from an empty JTextField, nor is an empty String (i.e. ""). How can I determine the JTextField did not have anything entered into it when the button was clicked?
 
i think the empty string comparison should work. except that you will need to use the equals method in the comparison. e.g.

if(yourJTextField.getText().equals(""))

hope this helps


 
actually this should work with null as well, that is the value that is returned, its just that you have to remember that getText() returns a String object, so you must use the equals method.

if(yourJtextField.getText().equals(null))

should also work.

You only use the double equals on Strings == to check if the two String references are in fact pointing to the same object. (java, correct me if i am wrong anyone, mainly uses references rather than values blah blah blah)
 
I tried the first solution,

if(jTextField1.getText().equals("")){
...
}

and it worked. The second solution,

if(jTextField1.getText().equals(null)){
...
}

did not work. I will use the first solution. Thanks for the help.
 
Or, you could check against the length of the string taken from the JTextField:

String s = textField.getText().trim();
if (s.length() = 0){

//JTextField is empty...

}

I usually use the trim( ) method just to be safe in case someone just presses the space bar a couple of times in the text field, it will eliminate all whitespace. ------
KJR
 
ok, i need to go and recheck the null thing, glad to be of service.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top