0

I have a textfield called x.

When the textfield contains " ", I want to do something. If it does not, do something else.

I tried doing

String test = x.getText();
if(test.startsWith(" ")){buttonN.setForeground(Color.GRAY));}
else{buttonN.setForeground(Color.BLACK));}

but it didnt work. any suggestions

razshan
  • 1,128
  • 12
  • 41
  • 59

4 Answers4

1

The easiest solution for any verifycation of the getText() command is this:

If (field.getText().isEmpty()) {
    buttonN.setForeground(Color.GRAY);
} 
else {
    buttonN.setForeground(Color.BLACK);
}
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
D-Dog
  • 11
  • 1
1

Why not use contains?:

 if(x.getText().contains("\u0020"))
    buttonN.setForeground(Color.GRAY);
 else
    buttonN.setForeground(Color.BLACK);

Although the aforementioned will work, it won't detect tabular spacing. That being said, I'd recommend using a regular expression instead:

if(Pattern.compile("\\s").matcher(x.getText()).find())
    buttonN.setForeground(Color.GRAY);
else
    buttonN.setForeground(Color.BLACK);

Reference.

mre
  • 43,520
  • 33
  • 120
  • 170
  • 2
    Why would you use the unicode value for the space? I hope you don't use "\u0060" when you search for an "a" (if thats what the unicode value is). You should not use magic numbers. – camickr Apr 22 '11 at 03:05
  • @camickr: WOW, would you feel better if I assigned the "magic number" to a variable ... `private static final String SPACE = "\u0020";`? Or better yet, if I had just used `" "`? Quit nitpicking ... – mre Apr 22 '11 at 10:09
  • 1
    It is not nitpicking. Tthe person asking this question is obviously a beginner. Many beginners just use the presented suggestion word for word without understanding the importance of all the code. Your solution should encourage good programming techniques. Many people may know what unicode 20 represents, but I'm guessing far fewwer people know what \u0056 represents. The code you write should be self documenting. My suggestion was to use " ", which leaves know doubt about whay you are searching for. – camickr Apr 22 '11 at 14:40
1

If you just want to ensure if the text field is empty regardless of whether it contains space, tab, newline etc. use the following:

if(x.getText().trim().length() == 0){
    buttonN.setForeground(Color.GRAY);
}else{
    buttonN.setForeground(Color.BLACK);
}

The String.trim() removes any whitespace in the String.

Suresh Kumar
  • 11,241
  • 9
  • 44
  • 54
0

(Color.GRAY)) and (Color.BLACK)) end with 2 closing parenthesis, while only one was opened.

String test = x.getText();
if (test.startsWith (" "))
{ 
     buttonN.setForeground (Color.GRAY); 
}
else buttonN.setForeground (Color.BLACK);

Some spaces around parenthesis make the reading more convenient.

user unknown
  • 35,537
  • 11
  • 75
  • 121