Swing 组件监听自身与内部类
我刚刚收到关于大学项目的一些不好的反馈,需要一些公正的澄清;
谁能解释我何时应该使用(匿名)内部侦听器类与侦听自身的组件? (a vs b)
a)
public class myButton extends JButton {
public myButton() {
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handling code...
}
});
}
}
b)
public class myButton extends JButton implements ActionListener {
public myButton() {
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
// handle the event
}
}
谢谢大家, 米奇
I just got some bad feedback on a uni project and need some impartial clarification;
Can anyone explain when I should use (anonymous) inner listener classes vs components that listen to themselves? (a vs b)
a)
public class myButton extends JButton {
public myButton() {
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handling code...
}
});
}
}
b)
public class myButton extends JButton implements ActionListener {
public myButton() {
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
// handle the event
}
}
Thanks guys,
Mitch
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
c)
c)
对于具有不同行为的多个按钮的情况,为每个按钮分配一个单独的匿名类会更方便,您仍然可以在类中实现 ActionListener 并根据源处理事件:
For cases where you have multiple buttons with different behavior it is more convenient to assign a separate anonymous class for each button, you can still implement ActionListener in your class and handle the event according to the source:
我认为这可能是个人喜好。不管怎样,我总是会选择内部类作为分离职责和组织代码的一种方式。
特别是,它们是使用 Adapter 类(已经实现某些特定 Listener 接口的空类,因此您只需要覆盖您需要的方法,而无需提供您不需要的方法的空实现)的唯一方法需要)。
I think it may be a personal preference. Anyway I would always go for inner classes as a way to separate responsabilities and organizing the code.
In particular, they are the only way to use the Adapter classes (empty classes that already implement some particular Listener interfaces, so you only need to overwrite the methods you need and you do not need to provide an empty implementation of those that you do not need).
要点是,当您声明
myButton
类来实现ActionListener
时,您增加了其可见的 API(即添加一个新的公共actionPerformed()
方法) ,可由任何持有myButton
引用的代码自由调用)。由于您可能不希望“
actionPerformed
”成为myButton
API 的一部分,因此您应该使用内部类,它将保留myButton 的公共 API
。请注意,Swing 类充满了不好的示例,例如公共方法被显式注释为“实现细节,不要直接调用”,实际上是非常糟糕的设计决策。
The point is that when you declare your
myButton
class to implementActionListener
, you increase its visible API (ie add a new publicactionPerformed()
method, freely callable by any code that holds a reference to amyButton
).Since you probably don't want "
actionPerformed
" to be part ofmyButton
API, you ought to use an inner class, that will preserve the public API ofmyButton
.Note that Swing classes are full of bad examples like that where the public methods are explicitly commented as "implementation detail, do not call directly", very bad design decision actually.