Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this method work?

Tags:

java

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.

like image 818
Suhail Gupta Avatar asked Jan 29 '26 16:01

Suhail Gupta


1 Answers

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.

like image 125
Zach L Avatar answered Jan 31 '26 07:01

Zach L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!