问题
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
回答1:
c)
JButton myButton = new JButton();
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handling code...
}
});
回答2:
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:
void actionPerformed(ActionEvent e) {
if (e.getSrouce() == button1)
{ ... }
else if (e.getSource() == button2)
{ ... }
// ...
}
回答3:
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).
回答4:
The point is that when you declare your myButton
class to implement ActionListener
, you increase its visible API (ie add a new public actionPerformed()
method, freely callable by any code that holds a reference to a myButton
).
Since you probably don't want "actionPerformed
" to be part of myButton
API, you ought to use an inner class, that will preserve the public API of myButton
.
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.
来源:https://stackoverflow.com/questions/5856083/swing-component-listening-to-itself-vs-inner-classes