ActionListener not doing anything [duplicate]

我的未来我决定 提交于 2019-12-11 05:29:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!