I would like to apply the MVC design to my Java application using Swing in a meaningful way. Therefore my question is, how the controllers would be structured in Java Swing?
For a clear separation of View and Controller, you could do it like this:
public class MyView extends SomeSwingComponent {
private Controller controller;
public View(Controller controller) {
this.controller = controller;
JButton saveButton = new JButton("Save");
button.addActionListner(controller.getSaveButtonListener());
}
}
public class MyController implements Controller {
private ActionListener saveButtonListener;
@Override
public ActionListener getSaveButtonListener() {
if (saveButtonListener == null) {
saveButtonListener = new ActionListener() {
// ...
}
}
}
Now we could implement different controllers which could be convenient, if we want to use the view component with different models. The controller is a strategy of the actual view instance.
In most cases it is just enough to define listeners as anonymous classes, because they usually just call a method on the controller instance. I use listeners usually as simple dispatchers - they receive a notification and send a message to another object. A listener class should implement too much business logic, that's beyond its responsibilties.