MVC从视图

时间:2016-04-05 18:16:43

标签: java swing model-view-controller

我正在使用MVC模式实现一个应用程序,在某些情况下,我从视图中创建了模型和控制器,并在视图中调用了控制器的相应方法。这是一个设计问题,如果可以解决的问题,我不能在主要模型中创建所有模型,因为其中一些模型是通过GUI点击来调用的。

这是一个示例代码:

public class MyView extends JInternalFrame{

private JComboBox<String> myList;
private JButton button;

public MyView(){
    super("MyView", true, // resizable
            false, // closable
            false, // maximizable
            true);// iconifiable
    setSize(250, 150);

    setLocation(300,300);

    myList= new JComboBox<String>();

    button= new JButton("Click");
    button.addActionListener(new Listener());

    JLabel label = new JLabel("Example");

    Border lineBorder = BorderFactory.createTitledBorder("Example UI");
    JPanel panel= new JPanel();
    panel.setBorder(lineBorder);
    panel.setLayout(new GridLayout(3, 1));
    panel.add(label);
    panel.add(list);
    panel.add(button);

    add(panel);
}

class Listener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        String button = actionEvent.getActionCommand();

        if(button==button.getText()){
            Model model = new Model ();
            Controller controller = new Controller (model, MyView.this);
            controller.doSomething();
        }

    }
}

1 个答案:

答案 0 :(得分:0)

经过一周的研究,我得出结论,我做的方式很好。用户与视图交互,该视图与控制器交互。没有惯例在哪里以及如何创建模型和控制器。这一切都取决于具体的问题模式。只要应用MVC的主要原则,你就是自由的。

相关问题