user2168435
user2168435

Reputation: 762

Swing actionPerformed method

I am testing an application that directly implements ActionListener

The below application can be compiled and run:

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");
        }
    });

}

}

But Eclipse wants the

public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}

method in App class as well. is this because the "go" method may sometimes not be called making actionPerformed not called and then against how implementing works? Thanks in advance for any assistance.

Upvotes: 0

Views: 9425

Answers (1)

Juned Ahsan
Juned Ahsan

Reputation: 68715

This is simply because of the java rule for implementing an interface. ActionListener interface has actionPerformed method in it. So any class implementing this interface need to provide the implementation for actionPerformed.

Read more about using ActionListener here: http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

Upvotes: 3

Related Questions