我经常遇到这种注册动作监听器的方法.
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
这里是一个:{
submit=new JButton("submit"); submit.addActionListener(new ActionListener(){ // line 1 public void actionPerformed(ActionEvent ae) { submitActionPerformed(ae); } }); //action listener added}调用的方法:
public void submitActionPerformed(ActionEvent ae) { // body }在这种方法中,我不需要实现ActionListener.为什么?
In this method, I don't need to implement ActionListener. Why?
另外,请解释标为第1行的代码的作用.
Also, please explain what the code labeled as line 1 does.
请清楚说明这两个摘要.
Please explain the 2 snippets clearly.
推荐答案从技术上讲,您确实实现了ActionListener.当您调用 addActionListener 时:
You technically did implement ActionListener. When you called addActionListener:
submit.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae) { submitActionPerformed(ae); } });您创建了 匿名类的实例> 或没有名称的实现 ActionListener 的类.
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());在您的示例中,匿名类仅调用您的成员方法之一 submitActionPerformed .这样,您的方法的名称可以比 actionPerformed 更具描述性,而且还可以在ActionListener之外的类中使用它.
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.
更多推荐
这种方法如何运作?
发布评论