First time posting a question on StackOverflow, so please go easy on me :)
From what I understand, proper use of the model-view-controller pattern requires that we decouple the view and controller such that the view knows nothing about the controller. I'm having a bit of a problem understanding how to do this using Java Swing.
Say I have a view (some class that would extend JFrame), and this view has a button. Is it safe to say that I would want to register the controller as an ActionListener of the button? Or do I make it a listener of the entire view itself.
And how do I go about doing this without doing something like:
button.addActionListener(myController)
in the view, because if I were to do this in the view code, wouldn't it now have a dependency on the controller?
I didn't post any code because, frankly I don't have much to go on at the moment.
any help is appreicated!
It might help to not think of the view in terms of buttons etc. so much as an interface. The interface makes it possible for web ui's, command line consoles, etc. to be written and fulfill the role of the view.
In the case of your button event, the button represents a call to some command carried out by the controller.
So, you could have an interface like this:
public interface MyViewIf {
// used by the controller to register its self as a listener of the view
public addViewListener(ViewListener vl);
...
}
and:
public interface ViewListenerIf {
// used by the View to notify any listeners of control events etc.
public onViewEvent(ViewEvent ve);
}
Then your controller would implement ViewListenerIf and register it's self with a factory generated instance of MyViewIf. That way the controller doesnt need to know any specifics about your view class(es).
Your view class would then internally handle it's own button events, turn them into ViewEvent objects and call onViewEvent() on the controller that registered it's self with the view, leaving the View 100% oblivious to the existence of the Controller.
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