Article View: borland.public.jbuilder.java.swing
Article #8350Re: basic jTextField question
From: John McGrath TeamB
Date: Sun, 24 Sep 2000 00:00
Date: Sun, 24 Sep 2000 00:00
42 lines
2125 bytes
2125 bytes
On Sat, 23 Sep 2000 22:22:14 -0400, Scott Howes wrote:
> if (jTextField1 = " ")
> jTextField1.setText("Add Text"); // incompatible types
>
> if (jTextField1.getText() = "")
> jTextField1.setText("Add Text"); // variable required but found
In Java (and C/C++), the "=" operator performs an assignment, not an
equality comparison. This is the equivalent of the Pascal ":=" operator.
The "==" operator is the equivalent of the Pascal "=".
But in Java, there is another twist. The "==" operator compares the
identity of two object references. It will return true if the variables
refer to the exact same object, not just two objects with the same value.
So it is quite possible for two string variables to refer to the same
string value, but not compare as equal using the "==".
The equals() method compares object values, which is what you want. So
instead of the above code, what you probably want:
if ( jTextField1.getText().equals("") ) ...
or perhaps:
if ( jTextField1.getText().length() == 0 ) ...
You also might want to check whether the field contains only blanks,
rather than just whether it is empty. If a user hits the space bar in
the field, it will not be apparent that the field contains a blank, and
the different behavior would be confusing. I have a string utility class
that has methods for performing tests like this, so I would write:
if ( StringUtil.isBlank( jTextField1.getText() ) ) ...
--
Regards,
John McGrath
---------------------------------------------------
Before sending me e-mail, please read:
http://www.JPMcGrath.net/newsgroups/e-mail.html
Technical Details
Message-ID:
<MPG.143759ca6a6d8925989b84@forums.borland.com>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<39cd626b_2@dnews>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 111d45,20f5a1ffaf32e238 X-Google-Attributes: gid111d45,public From: John McGrath [TeamB] <ng-b@JPMcGrath.net> Subject: Re: basic jTextField question Date: 2000/09/24 Message-ID: <MPG.143759ca6a6d8925989b84@forums.borland.com> X-Deja-AN: 673418797 References: <39cd626b_2@dnews> Organization: Another Netscape Collabra Server User Newsgroups: borland.public.jbuilder.java.swing