As others have suggested, you'll want to use assign a listener to the button, which will be called when the button is pressed.
Here's a incomplete example illustrating how to use an ActionListener
and implementing its actionPerformed
method which is called when the button is pressed:
...
final JTextField textField = new JTextField();
final JButton okButton = new JButton("OK");
okButton.addActionListner(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if ("some text".equals(textField.getText()))
System.out.println("Yes, text matches.");
else
System.out.println("No, text does not match.");
}
});
...
You may just want to implement ActionListener
in the class where the button and text field resides, so you don't need to declare the two objects as final
. (I just used an anonymous inner class to keep the example short.)
For more information, you may want to take a look at How to Write an Action Listener from The Java Tutorials.
Also, for general information on how events work in Java, the Lesson: Writing Event Listeners from The Java Tutorials may be useful.
Edit: Changed the expression inside if
statement from textField.getText().equals("some text")
to "some text".equals(textField.getText())
in order to prevent a NullPointerException
if textField
was null
, per suggestion from Mr. Shiny and New's comment.