1

I think you have understood what I am trying to do. Give a prompt when user press OK without changing he default TEXT. But the first condition seems to be TRUE. I don't know if it is a problem of if statement or my code.I have included the whole class .Be sure to read comment to avoid reading unnessasary code.

ok = JButton

text = JTextField

 int c = 0;
public  class handler implements ActionListener{
public void actionPerformed(ActionEvent e){ 
//
//The following lines are not nessary for the question.
if(ok==e.getSource()){
    if(!(male.isSelected() || female.isSelected()) && c==0){
      c++;
      JOptionPane.showMessageDialog(null,"Hey you haven't selected your gender. Do you wish to proceed","Warning",JOptionPane.PLAIN_MESSAGE);
     }
}
//well these lines were not necessary
//They were just in the same class
//
//
//Here the else condition should execute
//
if(ok==e.getSource()) && (text.getText() != "Enter your name")){
    JOptionPane.showMessageDialog(null,"Your name is "+text.getText(),"Name",JOptionPane.PLAIN_MESSAGE);
}else if((ok==e.getSource()) && (text.getText() == "Enter your name")){
    JOptionPane.showMessageDialog(null,"Hey type in your name buddy ","Name",JOptionPane.PLAIN_MESSAGE);
}
}
}

So the problem is that the if condition gets executed, while the else if should when we are not changing the default text "Enter your name". I tried changing the text and in that condition also the if block is executing. And please do a full explanation of your answer. I am a beginner with rusted skills.

1 Answers1

0

You need use other method to compare the strings, for example here:

text.getText() == "Enter your name")

you can use equals:

text.getText().equals("Enter your name")

You should do it in the two places into your original code.

Vasyl Lyashkevych
  • 1,920
  • 2
  • 23
  • 38
  • It worked. But only the second option. Can you please explain me what is the difference in using the first and the second option. But only in this format (text.getText()).equals("Enter your name"). As soon as I remove the parenthesis around text.getText() again it stops working. –  May 08 '17 at 06:42