我正在测试直接实现ActionListener的应用程序

以下应用程序可以编译并运行:

public class App implements ActionListener {

JButton button;
int count = 0;

public static void main (String[] args)
{
    App gui = new App();
    gui.go();
}

public void go()
{
    button = new JButton("Click me!");
    JFrame frame = new JFrame();
    frame.getContentPane().add(button);
    frame.setSize(500,500);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    button.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent event)
        {
            count++;
            button.setText("I've been clicked "+count+" times");
        }
    });

}

}

但是Eclipse希望
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}

App类中的方法。这是因为有时可能不会调用“go”方法,导致不调用actionPerformed,然后反对实现方式吗?
在此先感谢您的协助。

最佳答案

这仅仅是因为实现接口(interface)的Java规则。 ActionListener接口(interface)中具有actionPerformed方法。因此,任何实现此接口(interface)的类都需要提供actionPerformed的实现。

在此处阅读有关使用ActionListener的更多信息:http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

09-30 17:51
查看更多