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?
I have two options in mind:
- Every Component Listener is an own class, as part of the controller package
- Every Component Listener is an anonymous class inside the view package which delegates its call to a class with controller methods.
Is both possible? Is it a question of preference, or is it clearly defined?
Yes both is possible but I will prefer to write Single class which implements all actionListioner and assign that same to all component in your app. This way you can track all actions in your app at single point. Also this way you can make your view distinguish from controller.
in Swing components like
JButton
etc are the controllers. and all listener classes redirect events to model that have your business logicexample :
main program
View
controller
Model
For a clear separation of View and Controller, you could do it like this:
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.
Platzhirsch,
Dude, this a SERIOUSLY heavy-weight question... one which nobody is going to answer adequately in a forum post. This artice Java SE Application Design With MVC by Robert Eckstein (one of the Java Gods) discusses the problem at length.
Personally, I ended-up using a "variant" of MVC which I called MBVC (Model Business View Controller), which is actually pretty close to MVVMC... MVVM is widely used in .NET cirles; adding a controller made sense to me, as I had some web MVC experience. I wish I'd read the above article BEFORE I set-out to MVC-ise my app. You can still read my rather perplexed posts on Sun's (now Oracle's) Java forums.
Cheers. Keith.
While the Swing framework already implements a form of MVC (explicit models; JXyz & UI classes = controller & view), this strict separation is rarely used on application level and looks rather weird.
To start I suggest to follow the following design:
If you want to go a step further, use a RCP such as the NetBeans Platform (very recommended).
Look this MVC architecture