简体   繁体   English

向视图添加ActionListener的最佳方法

[英]Best way to add ActionListeners to the View

After reading some posts, I am not sure about the difference between these two ways to implement ActionListeners. 阅读一些帖子后,我不确定这两种实现ActionListener的方法之间的区别。 Is there any good reason to code in one way or another? 是否有充分的理由以一种或另一种方式进行编码? What about view-decoupling? 那么视图解耦呢?

OPTION 1: 选项1:

Implement getButton()/setButton() methods in the view, and use these methods to add ActionListeners in the controller. 在视图中实现getButton()/ setButton()方法,并使用这些方法在控制器中添加ActionListeners。

VIEW 视图

public JButton getBtnRun() {
        return btnRun;
    }

CONTROLLER 控制器

m_view.getBtnRun().addActionListener(new ButtonListener());

OPTION 2: 选项2:

Implement methods in the view, and call these methods from the controller, like here 在视图中实现方法,然后从控制器中调用这些方法,例如此处

VIEW 视图

public void setOpenFileAction(Action action) {
      displayText.setOpenFileButtonAction(action);
      fileMenu.add(new JMenuItem(action));
   }

CONTROLLER 控制器

view.setOpenFileAction(new OpenFileAction(view, model, "Open File",
            KeyEvent.VK_O));
  • IMHO It's better to have just one Swing Action . 恕我直言,最好只有一个摆动动作

  • If you eg enable/disable Swing Action it should enable/disable the JMenu and JButton as well. 例如,如果启用/禁用Swing Action则还应该启用/禁用JMenuJButton

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM