简体   繁体   中英

MVC architecture in Swing application

I have a question concerning MVC Swing java application.

Lets say, Entity e is simple class without any logic – only attributes and getters, setters, equals, hashCode, toString (or maybe compareTo). It will represent Model in MVC.

Than we have MainWindow (as the View in MVC).

Is it okay to use e.getSomething(); , e.setSomething(someValue); or even sort/iterate some collection of Element s in MainWindow ? And therefore do some GUI rendering and actions in component listeners anonymous classes (I guess listener implementation cannot be in Controller, because it's "view dependent" - HTML doesn't have listeners)?

I did something like this in MainWindow :

...
final Element el = Controller.getInstance().getSomeElement();
JButton save = new JButton();
JTextField field = new JTextField(el.getSomething());

save.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        el.setSomething(field.getText());
        Controller.getInstance().persist(); //let controller know some Element has changed and needs to be saved
    }
});
...

How to change this piece of code for it to comply with MVC? Thanks.

There's not a hard and fast rule; often the view and controller are combined in Swing apps.

However, in strict MVC, the view should not depend on the controller. The view simply listens to the model and draws itself, then exposes its components and events to the controller. The controller reacts to those events and alters the model as appropriate, which changes the view.

So, in your example, I would the following methods to MainWindow:

public void addSaveListener(ActionListener l) {
    save.addActionListener(l);
}

public void removeSaveListener(ActionListener l) {
    save.removeActionListener(l);
}

Furthermore, I would pass the instance of Element into the MainWindow constructor, so that it does not have to get it from the Controller. The Controller would be creating the MainWindow, passing its own reference in.

Then, in the controller:

myMainWindow.addSaveListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        el.setSomething(field.getText());
        persist(); // Element has changed and needs to be saved
    }
});

In larger apps, I would consider an event bus architecture instead of what I wrote above, but that is probably a different question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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