开发者

A Question about JTextField in Java

I met a small problem when running a Java class that I wrote, though the design is pretty straightforward. I've created a JPanel, and I've added four JTextFields onto it and I've attached a button to this JPanel, to开发者_JAVA百科o. Then, I've associated an ActionListener to this button being pressed. The code is like:

okButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) 
    {
       if (imageIdField.getText() == "" && 
           captionField.getText() == "" &&
           creditField.getText() == "" &&
           titleField.getText()== "") 
           {
              mediaXML = "";                        
              results.clear();
              results.put("error1", "more");

           } 
           else
           { ....
           }
    }

The strange thing is after I've pressed the OK button, and I did input text in those four JTextFields, still it will fall in the IF branch as if I didn't input any text in any of these four fields. I've been debugging this for a while, but no clue. Could anyone give me some hint like whether .getText() == "" is a valid way for testing no input?

Thanks in advance!


As has been mentioned, using == is not correct. For readability, try:

field.getText().isEmpty()

or

field.getText().trim().isEmpty()


Generally a bad idea to use == on Strings, or most other things. It checks that the objects are exactly the same instance, not that they have the same value. "" != new String("").

field.getText().equals("")

Or possibly better:

field.getText().isEmpty()


Use getText().equals("") instead of ==


Use == to check if it is the same object in memory, and .equals("YOUR STRING") to check if the content of the object is the same.


You should use .equals. Also, you might want to do something like this:

imageField.getText().trim().length() == 0  //The same for the others

or

imageField.getText().trim().isEmpty() //The same for the others

if you want to make sure that the user has actually written some characters instead of just white spaces.


== only checks whether the left hand side and the right hand side refer to the exact same instance of an object. And since "" translates to something like new String(""), it will always return false, if you compare it with a string that already exists.

If you want to compare whether two instances of a class have the same state you need to use equals(). In your case *.getText().equals(""). A more elegant method would to use the isEmpty() method of the String class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜