java - ActionListener 风格——好还是坏

标签 java swing coding-style inner-classes anonymous-class

<分区>

我有一个简单的 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)
       //...        
    }
}

现在我想知道这是否被认为是一种好/坏的风格?

最佳答案

除非监听器是一个很长的方法,否则我个人更喜欢匿名类模式:

        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);

甚至更好:

    btn.addActionListener(new ActionListener (){
         public void actionPerformed(ActionEvent e) {      
             // btn handling code
             }
    });
    rdb1.addActionListener(new ActionListener (){
         public void actionPerformed(ActionEvent e) {      
             // rdb1 handling code
             }
    });

您使用的模式允许其他类将类 TestApp 设置为其他类的监听器 - 除非有意,否则这不是一个好的做法。

关于java - ActionListener 风格——好还是坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317650/

相关文章:

java - 在代码的中间层声明一个局部变量好吗?

php - 您将如何映射或合并来自多个源/源的不同数据?

java - 一个类可以在哪三种不同的上下文中声明?

java - 当我添加新人员时,为什么我的目录程序中的添加方法将文本文件中的前四个字段设置为空?

android - 需要一个明确的答案来设计 Android ActionBar 选项卡

java - 访问循环中创建的各个 JTextField 的值

设置 jFrame.setUndecorated(true) 时不调用 Java WindowClosing 事件

javascript - 如何删除webview的标题

java - 如何使用java修改dxf文件

java - 如何将Java程序转换为Applet?