Mar*_*oun 3 java swing coding-style anonymous-class inner-classes
我有一个简单的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)
//...
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想知道这是否被视为好/坏风格?
除非监听器是一个很长的方法,否则我个人更喜欢匿名类模式:
final JButton btn = new JButton("Button");
final JRadioButton rdb1 = new JRadioButton("Value1");
final ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
if (e.getSource() == btn) {
//...
} else if (e.getSource() == rdb1) {
//...
}
}
};
btn.addActionListener(listener);
rdb1.addActionListener(listener);
Run Code Online (Sandbox Code Playgroud)
甚至更好:
btn.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e) {
// btn handling code
}
});
rdb1.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e) {
// rdb1 handling code
}
});
Run Code Online (Sandbox Code Playgroud)
您正在使用的模式允许其他类将类TestApp设置为由其他类设置为侦听器 - 除非这是预期的,否则这不是一个好习惯.