开发者

How does this method work?

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 开发者_JS百科:{

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜