2

I have often come across this way of registering an action listener.

Though I have been using this method recently but I don't understand how's and why's of this

Here is one :{

submit=new JButton("submit");
submit.addActionListener(new ActionListener(){       // line 1

  public void actionPerformed(ActionEvent ae) {
    submitActionPerformed(ae);
  }
}); //action listener added

} Method that is invoked :

public void submitActionPerformed(ActionEvent ae) {

    // body

}

In this method, I don't need to implement ActionListener. Why?

Also, please explain what the code labeled as line 1 does.

Please explain the 2 snippets clearly.

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

1 Answers1

9

You technically did implement ActionListener. When you called addActionListener:

submit.addActionListener(
 new ActionListener(){
  public void actionPerformed(ActionEvent ae) {
   submitActionPerformed(ae); 
   } 
  });

You created an instance of an anonymous class, or a class that implements ActionListener without a name.

In other words, the snippet above is essentially like if we did this with a local inner class:

class MyActionListener implements ActionListener
{
 public void actionPerformed(ActionEvent ae)
 {
  submitActionPerformed(ae);
 }
}

submit.addActionListener(new MyActionListener());

For your example, the anonymous class just calls one of your member methods, submitActionPerformed. This way, your method can have a slightly more descriptive name than actionPerformed, and it also makes it usable elsewhere in your class besides the ActionListener.

Zach L
  • 16,072
  • 4
  • 38
  • 39
  • 3
    and the reason you would want to use an anonymous class is so that the listener code is closer in proximity to the controls that use it. You would probably only want to use an anonymous class when the code required is relatively small, – MeBigFatGuy Mar 17 '11 at 05:37