I have a simple GUI which contains:
- a push button.
- Two radio buttons
Now I want to listen to each one of these buttons. What I do is something like that:
public class TestApp implements ActionListener {
private JFrame frame;
private JButton btn;
private JRadioButton rdb1;
private JRadioButton rdb2;
public static void main(String[] args) { /*....*/ }
private void initialize() {
//Each time I add a button, I add it to the listener:
btn = new JButton("Button");
btn.addActionListener(this);
//..
rdb1 = new JRadioButton("Value1");
rdb1.addActionListener(this);
//And so on...
}
//The ActionEvents
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn)
//...
if(e.getSource()==rdb1)
//...
}
}
Now I want to know if this considered a good/bad style?
Unless the listener is a very long method, I personally prefer the anonymous class pattern:
or even better:
The pattern you are using allows other class to set the class TestApp to be set as a listener by other classes – unless this is intended, it is not a good practice.