I want to use MVC to structure my Swing application, but there seems to be a conflict.
As I understand MVC, the controller should handle input and update the model. The model should notify its observers of which the view is one.
I have two problems
I'm sure this problem has been solved many times before, but I can't find a real world example of an MVC based swing app of a decent size.
Update - A problem I forgot
What MVC doesn't directly cater for is the structure of the various MVC components within the hierarchy of the application. For example, the main display may have "sales" and "purchasing" tabs, each of which might have "new" and "query" panels. On top of that, there may be an "amend selected" button which would create (possibly multiple) windows on request.
Something has to create a model,view and controller for these sub-components on request. It can't be the controller since the controller or model since they don't know which view to create and it shouldn't be the view since it's application logic and it's responding to an event (which is the controller's job).
Is there an answer?
Swing architecture is rooted in the model-view-controller ( MVC) design that dates back to SmallTalk . MVC architecture calls for a visual application to be broken up into three separate parts: A model that represents the data for the application. The view that is the visual representation of that data.
-MVC is an architectural pattern consisting of three parts: Model, View, Controller. Model: Handles data logic. View: It displays the information from the model to the user. Controller: It controls the data flow into a model object and updates the view whenever data changes.
The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. Each of these components are built to handle specific development aspects of an application.
Yes it is. The use depends on the type of application. And there are still a lot of application that work best with an MVC approach.
Swing components like JButton
etc are the controller. The view classes are JButtonUI
etc.
As for separating the event processing logic from your "view" code, the simplest thing is to inject a specific Controller
class into all of your panels. That way, event handling can just look like:
doStuffButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.doStuff(); // logic in controller
}
});
Your panel classes can offer up Model
s to your controller, so for example:
public void doStuff() {
MyData data = ...
dataModel.setData(data)
}
That way the controller is aware of the model, and the view is aware of the controller but the controller is unaware of the view (implementation)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With