我有一个简单的GUI,其中包含:
- 一个按钮。
- 两个单选按钮
现在我想监听这些按钮中的每一个。我会做类似以下的事情:
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)
//...
}
}
现在我想知道这种风格算是好的还是不好的?
ActionListener
来暴露你的ActionListener
是不好的风格,最好切换为内部类或匿名类。 - Robinrdb1.addActionListener(e -> {});
- Maroun