这种方法如何运作?

编程入门 行业动态 更新时间:2024-10-11 07:26:00
本文介绍了这种方法如何运作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我经常遇到这种注册动作监听器的方法.

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.

更多推荐

这种方法如何运作?

本文发布于:2023-11-25 23:22:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631758.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这种方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!