Ok so each text field the action listener. I’ve done many tests and found that adding the action listener is not the problem. The problem is somewhere in the below code because for the top four textfields, the hello window shows up but not the ok. But on the bottom one, the ok window and the hello window pop up. What did I do wrong?
public class handler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == text)
{
JOptionPane.showMessageDialog(null, "ok");
}
else if (event.getSource() == text1)
{
JOptionPane.showMessageDialog(null, "ok");
}
else if (event.getSource() == text2)
{
JOptionPane.showMessageDialog(null, "ok");
}
else if (event.getSource() == text3)
{
JOptionPane.showMessageDialog(null, "ok");
}
else if (event.getSource() == text4)
{
JOptionPane.showMessageDialog(null, "ok");
}
JOptionPane.showMessageDialog(null, "hello");
}
}
The problem you’re hitting is that you are doing a shallow comparison:
Thus, you never meet any of the conditions in your if-else and never see your “ok” dialog for text1 … text4.
It looks like you are attempting to use a single ActionListener for multiple text fields and then differentiate behavior based on the Event source (the text field on which the Event occurred).
Rather than doing that, you may want to consider creating an ActionListener implementation for each text field.
I typically create my ActionListeners as anonymous classes so I can customize what I want to happen for a particular field when an Event occurs, but I do not have to proliferate classes in my application.