-1

i would like to check whether the text in a text box matches a certain string. I have used an action listener, when the button is pressed it will check whether the text in the text box matches a certain word.

Thanks

This is what i have tried:

enter.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (txtbox.getText() == "cat") {
            txtbox.setText("correct");
        }
    }
});
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Rachel
  • 23
  • 1
  • 2
  • 8

2 Answers2

1

== is used to compare references and equals method (present in Object class) is used to compare the value of the objects. So in your case since you want to compare the value so consider using equals like

String myString ="cat";
if(myString.equals("cat")){
 //do something    
 }
Anugoonj
  • 575
  • 3
  • 9
1

== is used to check the reference.

equals is used to check the actual content at of the objects.

Below code shows how to update the JTextField.

final JTextField textField = new JTextField("cat");
JButton button = new JButton("Click");
// Code
button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if(textField.getText().equals("cat")) {
                    textField.setText("Changes");
                } else {
                    textField.setText("Already Changed");
                }
            }
        });
Amarnath
  • 8,736
  • 10
  • 54
  • 81