问题
I am new to Java, so please bear with me. I've tried to get a button to open up a new frame called AboutFrame, but whenever I press the button nothing happens.
I implement the ActionListener first:
class MainFrame extends JFrame implements ActionListener {
Then I set the button (after the usual super("blabla");...)
JButton info = new JButton("About Failsafe");
info.addActionListener(this);
And then:
public void actionPerformed(ActionEvent event) {
String command = event.getSource().toString();
if (command == "info") {
AboutFrame abt = new AboutFrame();
}
}
So what am I doing wrong here? I can't see any mistakes..
回答1:
You're not getting the command text correctly:
JButton button = (JButton) event.getSource();
String command = button.getText();
if (command.equals("About Failsafe"))
{
AboutFrame abt = new AboutFrame();
abt.setVisible(true);
}
Or, if your JButton info;
declaration is an instance variable (instead of a local one), you could make your if-check:
if (event.getSource() == info)
回答2:
Try:
if (event.getSource()==info) {}
instead of if (command=="info") {}
.
来源:https://stackoverflow.com/questions/22644909/actionlistener-not-doing-anything