Let’s say I have a button called button1. If I want to create an actionListener for the button which method should I choose: (In the second one, you have to extend actionListener interface)
// Imports
public class Test{
JButton test = new JButton();
Test(){
// Pretend there is an adapter
test.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
...
}
});
...
}
or
// Imports
public class Test2 extends ActionListener{
JButton button2 = new JButton();
Test2(){
button2.addActionListener(this);
}
// Pretend there is an adapter
public void actionPerformed(ActionEvent e){
Object src = e.getSource();
if(src == button2){
...
}else{
...
}
}
In the second case, you have to implement the
ActionListenerinterface. Other than that, the answer is “it depends”. If it makes sense to reuse the same action listener for several graphical components, then use the second version. If handling the event is a one-shot affair for a single component, then use the first version.