wood burning stoves*
The moose likes Swing / AWT / SWT and the fly likes How do I apply Model-View-Controller in Java Swing? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "How do I apply Model-View-Controller in Java Swing?" Watch "How do I apply Model-View-Controller in Java Swing?" New topic
Author

How do I apply Model-View-Controller in Java Swing?

Jonny Andersson
Ranch Hand

Joined: Sep 07, 2004
Posts: 87
I have been exercising for a way to build a good structure in an GUI application using the Model View Controller, MVC, architecture for a while now, and particularly how to apply it in a good way in a Java Swing application. Okay, for a small toy application is the structure maybe not that important. It may still be reasonably easy to read and understand the code. But for a large application that is part of a large library with a lot of views may it have a huge impact on how easy it is to understand, change, extend and reuse the code. And the structure gets quickly quite complex and tough to understand. So the big question is how MVC could be applied to Java Swing in a good way. Are there any people here that have opinions on how it should be done and would like to have a long interesting discussion about it? ... I�ll give it a try.'

When I say applied to Java Swing do I not talk about the micro MVC structure that already is applied to most of the available GUI widgets for Java Swing but instead to the macro structure for the architecture of the overall system.

If you google for discussions about MVC do you quickly find how misused that acronym is and I think that a lot of what is said about MVC is said of people that not have spent time enough to really try understand it. I don�t understand it very well myself yet despite I now have some years of experience from Java development. The best article I have found about MVC is this article in about 6-7 pages http://www.jdl.co.uk/briefings/mvc.html which discuss MVC as it was designed originally in SmallTalk. But the article is not very deep and don�t much details about how to apply it so I am trying to build a small toy application on myself to try it and have so far spent most focus on the model to view and view to model communication. Lets start there!

Everyone, I guess, have learnt that the model should no know anything about the view. Instead it is the view that should know its model. But the view needs to know if the model gets updated outside of the model. A key thing the article say about how to get this to work is to look at the model as a component with two parts, the domain model and the application model, and it is the application model that should know some about the view. Not more than necessary though.

For the view to model communication does the article say that "the views know about the model and will interact with the model". And it also say "it is then the model responding to the message to obtain values" when a message is sent about something that have happened in the view. For the model to view communication does the article say "the controllers and the model communicate with the view via events. Events provide nicely decoupled mechanics that allow communication, with minimal dependencies".

First, the controllers seem to be one of the most confusing thing in articles about MVC. In my view is the controller when applied to Java Swing just the action listeners applied to a GUI widget like a text field and nothing more. The important thing is the view and the model and one big question is then, who updates the model?

When an event have occurred in the view, new text in an input field for example, should the (application) model be notified from the action listener and then itself get the data from the view from some getters in the view? Or should the view call setters in the model to update the data? This is a more important question than it may look as. It have a lot of impact for the coupling between the view and its model and for the encapsulation of their implementation. I want, of course the coupling to be as low as possible (the really ideal would be if the view could be a plugin to model) and the encapsulation to be as strong as possible. With good encapsulation would it be easier to do changes in the view. And it would easier for other to use it if it exports (public) as few methods as possible. Few methods to learn about and in what order they may be called is easier than a huge amount of them.

If we look at the micro MVC used in Java Swing widgets is it the model that gets the data from the view (the widget) when I has been notified about a change through the listener. But from my exercises do I currently think that the model in the macro architecture not should know this much about the view. Instead do I think the view should update the model from the action listener (the controller!) as soon as a change have occurred. But the view should also be a listener to the model that should notify all its listeners as soon as anything in it have been updated. To decrease the coupling should the view know about its model through an interface that tells what setters and getters the model have and when it gets notified about a change in the model do it use getters to et the updated values. The model do only know about the view as an object that implement the interface for a listener that it recognizes.

I have a little UML model for this and wish it have been possible to include it here but I can�t. So I hope it was possible to follow the description above. And that I not have typed too many spelling errors and grammatical errors

But am I wrong? Is it instead the model that should call setters and getters in the view (class)? Like in the micro MVC used for the Swing widgets. I don�t like it because I think the model know a lot more about its view in that case. And it is more hard to have many view for one model. But it could be decoupled from its view a little if it knows about the view through an interface that every view implements. What do you think? Which of these strategies gives the most flexible design? And particularly WHY?

There is of course a lot more to discuss about MVC than this but the other details have to wait.
[ January 30, 2008: Message edited by: Jonny Andersson ]

Truly agile Java application developer with Extreme Programming and high quality craftsmanship
Jonny Andersson
Ranch Hand

Joined: Sep 07, 2004
Posts: 87
An UML-diagram that illustrates the MVC architecture described above:

http://www.lsn.se/andersson/mvc.jpg
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
Originally posted by Jonny Andersson:
I not talk about the micro MVC structure that already is applied to most of the available GUI widgets for Java Swing but instead to the macro structure for the architecture of the overall system.

[...]

But am I wrong? Is it instead the model that should call setters and getters in the view (class)? Like in the micro MVC used for the Swing widgets. I don�t like it


I would have to disagree with your claim that the models of Swing widgets call setters and getters in the view.

The way it is supposed to work is the models fire events, but that's all. The views listen to events and update themselves, but the models don't care if their listeners happen to be views or not. You mention this yourself in a preceding paragraph, so I'm not sure what you're getting at here.


Questions about the "macro structure for the architecture" are good to ask, but I'm not sure this is the best forum for it.


bitguru blog
Jonny Andersson
Ranch Hand

Joined: Sep 07, 2004
Posts: 87

I would have to disagree with your claim that the models of Swing widgets call setters and getters in the view.


Well, look at a JTextField. You add listener (a document listener) on it and when it gets fired do you get the text content by a call of getText() on the text field (well, or actually on the document for the text field). So logically do I think it is the model, or at least something outside the text field that gets the data by a call of its getter. But I don�t think this is that bad because the text field is usually part of (and then encapsulated in) a larger composite view.

But the big question is how to get the data from that view to the application model which know what to do with that data, for example store it to a file or a database, and which contains business logic. Either does the application model get the data from the view by call of getters in the view, getters that probably pick the data from the widgets. Or does the listeners in the view, for example the listener on the text field. call setters in the application model to set the new data. And as I have understood is it the view that call setters in the application model and not the opposite. Which I think is what you also said.

But there is other things to consider also when the communication between the application model and the view is designed. For example where is the validations made and where is the messages to display for the user created? It is not easy to tie it all together with loose coupling and high encapsulation.


Questions about the "macro structure for the architecture" are good to ask, but I'm not sure this is the best forum for it.


Maybe you are right, I have also considered if this really is a good forum to discuss this but I don�t know about any better alternatives. Do you have a suggestion for a better forum to discuss this and/or a better way to learn more about it? I think it would be really valuable to learn more about this for everyone that is creating Swing applications.

Thank�s for your reply!
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
Originally posted by Jonny Andersson:

Well, look at a JTextField. You add listener (a document listener) on it and when it gets fired do you get the text content by a call of getText() on the text field (well, or actually on the document for the text field).
The JTextField is not the model. Its Document is the model. The JTextField itself is the view (or perhaps a view/controller hybrid). Hence you can do something like to display four fields locked with the same content.

You can't add a DocumentListener to the view (to the JTextField) but you certainly may add one to the model (in this case a PlainDocument, but it could be any Object you want so long as it implements the Document interface).

When the view receives a DocumentEvent it may, as you say, call getText() on the model but that's consistent with MVC, no?

But the big question is how to get the data from that view to the application model which know what to do with that data, for example store it to a file or a database, and which contains business logic.
First, you don't get the data from the view. You get it from the model. Yes, you can call myTextField.getText() but that's just a convenience wrapper for myTextField.getDocument().getText().

You can store the model wherever you want. You could even create an implementation of Document in which getText() queries a database and insertString()/replace() updates a database. I wouldn't recommend it (due to latency issues, among other things) but you could do it.


Just about the only Swing widget that doesn't have a model is JLabel. Even buttons have models (see ButtonModel, DefaultButtonModel, ToggleButtonModel).
[ January 30, 2008: Message edited by: Brian Cole ]
Jonny Andersson
Ranch Hand

Joined: Sep 07, 2004
Posts: 87
Thank�s. I agree in all that. But all these text fields and buttons are usually added to a container, for example a subclass of JPanel (but I would prefer to wrap/encapsulate them instead) which becomes a visual "view" embedded in a frame or another window. And how do you then export the data from that view? Do you add public getters to the panel subclass to get the data from the models of the widgets? Or do you add the class to which the data should be exported (a class that I call the application model where business logic is applied on the data) as a reference/member of the panel subclass and let the "view" itself export the data by call of setters in the application model? It is the design at this module level of the structure that I not am sure about.
[ January 30, 2008: Message edited by: Jonny Andersson ]
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
Originally posted by Jonny Andersson:
But all these text fields and buttons are usually added to a container, for example a subclass of JPanel (but I would prefer to wrap/encapsulate them instead) which becomes a visual "view" embedded in a frame or another window. And how do you then export the data from that view?


If you are a true believer in MVC then you just plain don't want to get data from the view.

If you gather all the data in some kind of "data model" class, for instance, then your "view" panel would display/modify the data in that class. There would be nothing to "export" because the data you need is just sitting there in a convenient form in your data model.

Do you add public getters to the panel subclass to get the data from the models of the widgets? Or do you add the class to which the data should be exported (a class that I call the application model where business logic is applied on the data) as a reference/member of the panel subclass and let the "view" itself export the data by call of setters in the application model?


The two options you present here seem to be (A) the application model pulls data from the view, and (B) the view pushes data to the application model.

I could go either way on the pulling/pushing issue, but shouldn't the application model be interacting with the data model, not with the view? The application model shouldn't even care about the view(s), right?
[ January 31, 2008: Message edited by: Brian Cole ]
Jonny Andersson
Ranch Hand

Joined: Sep 07, 2004
Posts: 87
If you are a true believer in MVC


I think I am that�s the reason to this topic. And it is always exciting to discuss how to achieve a flexible good object oriented design.


There would be nothing to "export" because the data you need is just sitting there in a convenient form in your data model.
...
The two options you present here seem to be (A) the application model pulls data from the view, and (B) the view pushes data to the application model.


Okay, but lets think on a dialog window where insert of a value maybe should cause some other value in that dialog, or maybe in another open window, to be recalculated according to some business logic. I think that business logic should occur in some other class, which I call the application model, outside of the view. The application model should not know from where it got the data, only that it just got some data and now have to calculate on it AND notify all views that is listening on that application model that there have been a change. So the question is then how the data is, well lets call it transferred then, to the application model. Pull or push?


The application model shouldn't even care about the view(s), right?


Yes! I really agree! And therefore I think it is the view that should push it to the application model. BUT the view also needs to know when the applicatiation model has changed so that it can request the updated data to show it! The first change is probably when some logic in the application model has loaded data from somewhere just before it should be displayed the first time in the view. And to notify the view does the application model have to know a little about it, as some listener it has to notify. Look at this UML diagram if you not have it already:

http://www.lsn.se/andersson/mvc.jpg

I have tried to sketch the above architecture in that model. But I don�t yet know if this is the "right" way to go or if it has some serious disadvantages. Or if it just is unnecessary complicated.

I agree in that the application model should know as little as possible about its view or views. But the domain model should know nothing at all! In that case is it just the application model that push all of its data to the domain model which in the case of a file storage is just some sort of data structure without much logic. This separation of the model in a domain model and a application model is just what is described in this good document in only about 6-7 pages. Read it if you not already have because it is a really good description about MVC. But it is not very detailed:

http://www.jdl.co.uk/briefings/mvc.html

it is much of the principles in that document I try to follow in the MVC architecture I have sketched in the UML model.
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
Originally posted by Jonny Andersson:
Okay, but lets think on a dialog window where insert of a value maybe should cause some other value in that dialog, or maybe in another open window, to be recalculated according to some business logic. I think that business logic should occur in some other class, which I call the application model, outside of the view. The application model should not know from where it got the data, only that it just got some data and now have to calculate on it AND notify all views that is listening on that application model that there have been a change.


From this I gather that we're not completely eye-to-eye on the terminology, because I would think the application model does sort of need to know where it got the data. The application model would register itself as a listener to what I've been calling the "data model." If you disagree then we probably have different ideas about what exactly the application model is.

I would think an MVC implementation of this situation would go like this. When the user inserts the value on the dialog view the view calls a setter in the data model, then the data model fires an even to all listeners. That other dialog is a listener, so it can update that field you're worried about. The application model is also a listener so it knows when to perform its recalculations and whatnot. The application model might end up calling some setters in the data model, which will cause the data model to fire more events so all the views can updates themselves.
Jonny Andersson
Ranch Hand

Joined: Sep 07, 2004
Posts: 87

From this I gather that we're not completely eye-to-eye on the terminology, because I would think the application model does sort of need to know where it got the data. The application model would register itself as a listener to what I've been calling the "data model." If you disagree then we probably have different ideas about what exactly the application model is.


We should have this discussion live in front of a whiteboard instead because it would be a lot easier to describe a structure using a drawn UML model instead of just using words. But I can�t say that I disagree. I just only have an interpretation of the "domain model to application model to view" architecture from http://www.jdl.co.uk/briefings/mvc.html which I try to figure out and I am ready to accept other interpretation of it if it is supported with good arguments.


I would think an MVC implementation of this situation would go like this. When the user inserts the value on the dialog view the view calls a setter in the data model, then the data model fires an even to all listeners. That other dialog is a listener, so it can update that field you're worried about. The application model is also a listener so it knows when to perform its recalculations and whatnot. The application model might end up calling some setters in the data model, which will cause the data model to fire more events so all the views can updates themselves.


This is a different way to structure this that I not have thought about before. It looks reasonable because you separate the business logic from the view as I also want it but it is different in the way that the application model is listening on the same thing as the view does. That sounds a bit strange. Is the model then something that keeps data, something that represents what is described as the domain model in http://www.jdl.co.uk/briefings/mvc.html? In that case am I not sure I will agree in that because I think the reason to separate the model in two parts, the application model and the domain model, is to have a domain model that knows NOTHING about its views. But that is impossible if the views need to be notified when the data change. Notification is the job for the application model. I need to understand more on why this is better before I am ready to accept it.

I have maybe not been clear enough yet about the thing I call the application model. For me is the application model not something that keep the data itself. Instead it just transfer it to and from the domain model. For example an Integer would be a good representation of a domain model object. It is data only without any listeners or any other connection to other objects. A data structure that has Integers and maybe other member variables to keep just data as members would also be a good domain model object.

The application model is associated with domain model objects, probably as member objects. How strong this association is (in UML terms am I uncertain on). But the application model do also notify the views when the data in the domain model is changed. In that way is it different from the domain model, it knows something about the view, but preferably as little as possible.

The application model is then also the "module" that has the business logic. For example to save the data by insertions/updates to a database or serialization to a file when the user have requested it by an action in the user interface. An it is the module that knows business rules to be performed on the data.

I am uncertain if it would be better to have application model also be a listener of the (domain) model as the views is. But the way I describe it is maybe unnecessary complicated, I don�t know. The view would be tightly coupled to the application model if it need to know a lot of methods that corresponds to all data it must be able to transfer to the domain model through the application model. But that may be milded if it knows about the application model in form of an interface. But the application model may have to implement several interfaces then.

And what about validation for example? Sometimes may validation be complicated business logic, that should go in the application model then. But display of user messages should be done in the user interface, the view. And then do we have to communicate this as well between the application model and the view. It would be easier to just pop up a message dialog right from the application model, but then is it doing view tasks. Well, maybe it is impossible to be 100% pure on MVC.

I don�t know if I really have got that much better understanding on this yet. But I absolutely like this discussion about it with you. Most of the details about Swing can be found in books and tutorials on the web. But I have never found any good books about this high level of structure, at the level of architecture. And it is hard to learn it on yourself.
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
Originally posted by Jonny Andersson:
This is a different way to structure this that I not have thought about before. It looks reasonable because you separate the business logic from the view as I also want it but it is different in the way that the application model is listening on the same thing as the view does. That sounds a bit strange.


It seems to me that that's the way it should be.

No surprise there, since it's my own description that I'm agreeing with, but if the view(s) need the data and the application logic(s) needs the data why shouldn't they obtain it the same way? It seems like a no-brainer to me.

Is the model then something that keeps data, something that represents what is described as the domain model in http://www.jdl.co.uk/briefings/mvc.html?


Yes to the "something that keeps data" part. That's why previously in this thread I sometimes called it the "data model."

I'm not sure exactly what the article means by "domain model," so I can't answer that part. "The domain model will consist of the objects which represent and support the essence of the problem�MagneticField, Client, Invoice, Booking, ..." So does he mean the holders of the data (essentially a set of .class files) or the data itself? (I'm not necessarily a "true believer" in MVC, so I don't really care if I agree with an article. I do care whether or not I have a nice, clean, solid design.)

In that case am I not sure I will agree in that because I think the reason to separate the model in two parts, the application model and the domain model, is to have a domain model that knows NOTHING about its views.


I agree that the data model should know nothing about its views. All it knows is that it needs to send events to any listeners it may have.

What you seem to have a problem with (if I have understood some of your previous posts correctly) is that the application logic should know about the data model. I think it should, so I have no problem with that. I'm not sure how things could work otherwise. (Well I guess you could use a something like InfoBus if you really wanted to.)
[ February 01, 2008: Message edited by: Brian Cole ]
Jonny Andersson
Ranch Hand

Joined: Sep 07, 2004
Posts: 87
Thanks for your opinions and advices. I will try to apply your advices from our discussion here in a little template application I am plying with at my spare time and see what I can learn from that. But as long as there not are made more replies to this thread do I stop watching it now and instead put a bit more prioritization on a little certification I have to clear off. Thanks for all your replies! It have been valuable to read them!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How do I apply Model-View-Controller in Java Swing?