1

I'm trying to program an swing application and learn something about the mvc pattern. Also I want to keep my Swing Code clean, so I split up my GUI in different classes. A part of this class structure looks like this:

//all classes extending BasicGuiElement
-EntireContentElement  has:
---ControlElement  has:
------MainMenuElement

MainMenuElement contains the MainMenuBar, the Menu's and the MenuItems. Now, different MenuItems need different ActionListeners.

And here is my Problem: Where should this ActionListener's come from? Should i create the EntireControlElement in the View, to which i pass an HashMap and also pass this map through all the elements to MainMenuElement? And if i have many classes who all needs a bunch of action listeners, i would pass a list of listener maps? That would be really ugly code, would'nt it?

Another solution would be to pass the Model as the ModelInterface to the View, and call model methods from the action listeners, which would be created in the view classes... would that be a nicer approach?

Thank you!

T_01
  • 1,256
  • 3
  • 16
  • 35
  • 1
    The model and view, generally speaking, shouldn't know about each other and should be bridged by the controller, this means that the controller should be acting as a observer to the view and responding to appropriate events. One thing you could do is define a contract between the view and the controller which describes the actions which the view can perform (or even a generic "menu event") to which the controller can react to. You would the attach `ActionListener`s to your components within the view directly, but then trigger the appropriate events back to the controller. – MadProgrammer Apr 01 '15 at 22:59
  • 1
    Kind of demonstrated the idea [here](http://stackoverflow.com/questions/26517856/java-swing-where-do-actionlisteners-belong-according-to-mvc-pattern/26518274#26518274) – MadProgrammer Apr 01 '15 at 22:59

1 Answers1

2

As an alternative to @MadProgrammer's nice example in his comment, there's a lesser known pattern called MVP (Model-View-Presenter). It's a variant of traditional MVC where the goal is to make the view as dumb as possible (no knowledge or references to models, controllers, or any other application code) so that all code to be tested is out of the GUI.

To answer your question using MVP, the Model is "stand-alone" and knows nothing of Views or Presenters/Controllers. Likewise, the View is also "stand-alone" and knows nothing about Models or Presenters/Controllers. The Presenter is a bridge between both who injects listener logic into the View.

For compare/contrast, there's an MVP example that can be seen here, that is a rewrite of an MVC example seen here.

See also:

Wiki: Model-View-Presenter

ObjectMentor: The Humble Dialog Box

Community
  • 1
  • 1
splungebob
  • 5,357
  • 2
  • 22
  • 45