【问题标题】:Add a listener inside or outside get method在 get 方法内部或外部添加侦听器
【发布时间】:2011-02-23 04:04:20
【问题描述】:

我正在学习 Swing,并使用一系列 get 方法组成了一个界面来添加组件。如下在 get 方法中添加监听器是一种好习惯吗?我想让事情尽可能地解耦。

 private JButton getConnectButton() {
  if (connectButton == null) {
   connectButton = new JButton();
   connectButton.setText("Connect");
   connectButton.setSize(new Dimension(81, 16));
   connectButton.setLocation(new Point(410, 5));

   connectButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
     // actionPerformed code goes here
    }
   });

  }
  return connectButton;
 }

【问题讨论】:

    标签: java swing components event-listener


    【解决方案1】:

    根据我作为 Swing 开发人员的广泛实践,我可以告诉您,以这种方式(通过 getter)获取组件实例并不是一个好习惯。我通常在 initComponents() 等方法中为 Frame/Dialog 设置 UI,然后在 addListeners() 等方法中添加所有侦听器。我不确定是否有一个最佳实践作为如何做事 - 有很多选择和个人喜好。但是,通常不需要您无论如何都需要的组件的惰性初始化(比如我认为的这个按钮)。

    另外 - 你真的应该考虑使用一些布局管理器,例如 MiG,并避免硬编码组件大小。

    【讨论】:

    • 另外,我建议将组件定义为私有 final 并在其声明中直接实例化它们。
    • 仅当需要从框架/对话框的其他部分访问它们时。例如,标签在大多数情况下甚至不保证局部变量。不会有条件地启用/禁用的按钮也不需要是字段。我认为没有通用的配方 - 这完全取决于情况。但当然应该努力减少字段的数量。
    • 我很欣赏涉及经验的反馈。告诉我,您通常如何组织组件?您是否有一个大型的单体类,其中描述了所有组件,或者您将它们放入单独的面板类中?我也听说过 MiG 的好消息,我会试一试。
    【解决方案2】:

    您似乎正在对connectButton 进行一些延迟初始化。这可能很好,不过,我会这样做:

    private void createButton() {
        connectButton = new JButton(new AbstractAction("Connect") {
            public void actionPerformed(ActionEvent e) {
                // actionPerformed code goes here
            }
        });
        connectButton.setText("Connect");
    
        // Rely on some LayoutManager!
        //connectButton.setSize(new Dimension(81, 16));
        //connectButton.setLocation(new Point(410, 5));
    }
    
    private synchronized JButton getConnectButton() {
        if (connectButton == null)
            createButton();
    
        return connectButton;
    }
    

    注意synchronized 的使用。它确保不会发生以下情况:

    • 线程 1 调用 getConnectButton() 并看到 connectButton == null
    • 线程 2 调用 getConnectButton() 并看到 connectButton == null
    • 线程 1 调用 createButton
    • 线程 2 调用 createButton。

    可能有更好的方法来同步按钮构造,但这是一种方法。

    【讨论】:

    • 谢谢。我不知道在 Swing 中可以使用惰性初始化方法。这就是可视化编辑器对组件进行编码的方式。我会在需要时保留您的回复副本以备不时之需。
    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2017-12-31
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多