I've implemented MVC pattern for Java SE with Swing using PropertyChageSupport
and PropertyChageListener
. The diagram for implemented MVC is as follows.
In the implementation of View
, I do property change in Model
with the help of Controller
.
View
contains code like following for Ok button.
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
modelController.setNumber(Integer.parseInt(numberField
.getText()));
modelController.setName(nameField.getText());
}
});
Complete code can be found in SwingMVC.
Now, My question is, Do I write above code for btnOk
in View
or Should I write it in a method in Controller
so that in View
, I'll be doing
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
modelController.btnOkActionPerformed();
}
});
Of above two implementations, Which is the preferred way to implement MVC?
Your diagram suggests a model–view–presenter (MVP) pattern, which is compatible with Swing application design. In this context,
Action
is a convenient way to encapsulate application functionality for export from you model. As concrete examples:DefaultEditorKit
andStyledEditorKit
export usefulAction
types that operate on theDocument
model common to text components. As shown in this example, such actions update theDocument
, which indirectly updates the corresponding view component.The
ControlPanel
in the example cited here exposes a number ofAction
instances that operate directly on an implicit model ofList<Node>
andList<Edge>
.First a caveat: I'm not a professional or student but a hobbiest, but having said that, my own preference is with your second example,
The control would have to call methods on the view to extract information, and any methods it would call would be part of an interface that the view implements. My goal in this is to keep the view as dumb as possible and do almost anything to loosen coupling as much as possible.