I am currently having difficulty in testing a condition if a certain button do not have a text on it.

For example i have a button in an array named btn[] and a textview(JLabel) named "tv", if i execute this code, nothing happened.

if(btn[1].getText().toString().isEmpty()){
            tv.setText("Okay");
        }

i also tried these following codes:

if(btn[1].getText().toString().equals(null)){
                tv.setText("Okay");
            }



if(btn[1].getText().toString().equals("")){
                tv.setText("Okay");
            }



if(btn[1].getText().toString().length()==0){
                tv.setText("Okay");
            }

is there something wrong with my code?
thanks for the replies

Recommended Answers

All 5 Replies

That all looks sensible. In general you need to test for null first, then if it's not null you can test for an empty String - if you want to treat a blank string as being empty, then use trim() first.
getText returns a String, so the toString() is not needed.

if (btn[].getText() == null || btn[i].getText.trim().length() == 0) ...

It looks like the button text is something else, or you are in some context where that code isn't being executed. Try printing the text and the length of the text to see exactly what you've got.

Thanks a lot JamesCherrill!
This code works like a charm :))

btn[i].getText.trim().length()

Thread closed..

br

OK! Looks like your button had one or more blanks as its text.
Please amrk this "solved" for our database.
Thanks
J

Try to se that way
if(btn[1].getText().toString()="")

commented: just read my reply for the 'why' -3
commented: unneccessary, unhelpful, didn't read thread, wrong -3

Ellena980:

something tells me this post is nothing but a way to advertise the links in your signature.

  1. the OP already had a similar line in his original post
  2. it shows that you are not all too familiar with OO concepts. you should have used the equals method (what the OP did, making your solution to his problem worse than the original problem)
  3. it might have been better if you argumented why the 'toString()' call there isn't necessary, rather than just to copy paste something that looks as if it makes sense.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.