【问题标题】:Dealing with MVC model, jbuttons and ActionListener's getSource() method处理MVC模型、jbuttons和ActionListener的getSource()方法
【发布时间】:2015-06-08 23:51:35
【问题描述】:

所以我在使用 MVC 编写程序时偶然发现了这个问题。 我在View 类中有一个私人 JButton。我编写了将侦听器添加到所有相应按钮的方法。但是,当我尝试对 ActionPerformed() 部分进行编码时,它会引发关于 JButton 不可见的错误。

JButton 设置为public 可以完全解决问题,但这样做是否正确?是否有另一种设置ActionListener 而不公开JButton 的方法?

public class learningView extends JFrame {
    private JButton viewButton = new JButton("View Resources");

    public void addButtonListener(ActionListener listenerForButtons) { 

    viewButton.addActionListener(listenerForButtons);
    saveButton.addActionListener(listenerForButtons);
    addButton.addActionListener(listenerForButtons);

    }
}

public class learningController {

    private learningModel theModel;
    private learningView theView;

    public learningController(learningModel theModel, learningView theView) {

    this.theModel = theModel;
    this.theView = theView;

    this.theView.addButtonListener(new buttonListener());

}

class buttonListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == theView.viewButton) {// This is where problem arises

        }

    }

}

}

为了方便起见,用于视图和控制器类(无模型)的 Hastebin。 http://www.hastebin.com/ecawolusal.avrasm

【问题讨论】:

    标签: java model-view-controller jbutton actionlistener private


    【解决方案1】:

    由于viewButton 拥有对LearningVew 的私​​有访问权限,因此无法从该类上下文中访问它。

    现在,在您更改访问级别之前,您可能会考虑更改您的方法。

    与其为通知外部源的每个按钮添加一个ActionListener,不如让视图来监控按钮本身可能更简单。

    在您开始讨论这将如何破坏 MVC 之前,我们的想法是让视图为相关按钮引发一个更简单、更专用的事件,例如,viewButton 可以引发 viewWasActivated或其他东西,然后控制器会对其做出响应。

    这将要求您为视图和控制器定义interface 契约,以便他们知道他们能够相互传递哪些信息以及可能触发哪些事件。这可以保护视图控件,并且意味着您不需要公开不必要的控件。

    更详细地演示了here

    另一种选择是使用按钮的actionCommand 属性,而不是将按钮的引用与事件源进行比较,但您首先需要检查操作事件的源是否是按钮...而且我个人不喜欢“散装”ActionListeners,它们很快就会变得一团糟......

    【讨论】:

    • 太棒了。非常感谢您的回答。我认为可以安全地假设 JavaFX 会更适合使用 MVC 模式的程序而不会遇到所描述的问题?
    • 我对 JavaJX 不够熟悉,但如果我记得,您仍然将“属性”侦听器直接附加到控件,因此您仍然会遇到类似的问题
    猜你喜欢
    • 1970-01-01
    • 2013-02-14
    • 2015-07-18
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2023-03-15
    • 2014-10-26
    • 2015-11-07
    相关资源
    最近更新 更多