This discussion is archived
3 Replies Latest reply: Dec 6, 2012 12:34 AM by TPD-Opitz-Consulting-com RSS

MVC for ActionListener

978140 Newbie
Currently Being Moderated
Hi. I am having one Main class(main-package) who creates GUI class(view-package). The GUI class contains JButtons.
Anyone have an idea how I can add ActionListeners for my JButtons in a "controll-package" without getting cyclic dependencies?

Example:

Main:
Gui gui = new GUI();
MyListener list = new MyListener(gui); // To allow the listener(controller) give feedback to GUI

GUI: Create a button and set its action to MyListener
MyListener list = new MyListener();
JButton a = new JButton();
a.addActionListener(list);

MyListener: Contains the gui and gives feedback to it after click
private GUI gui;

*public MyListener(GUI gui){*
this.gui = gui;
*}*

*public void actionPerformed(){*
gui.setMyTest("Button Clicked!");
*}*

But problem with this is the cyclic dependency I get. Any hint on approach?
  • 1. Re: MVC for ActionListener
    TPD-Opitz-Consulting-com Expert
    Currently Being Moderated
    You are missing the M in MCV.

    You need a data model that is modified by your ActionListener (after clicking the button) and that issues change notifications to registered ModelListeners (you gui components).

    bye
    TPD
  • 2. Re: MVC for ActionListener
    978140 Newbie
    Currently Being Moderated
    Ok, thanks. Tried to put the Listener into a Model-package but I then get cyclic dependencie for view->model->controller->view .... I guess it is expected and not possible to solve?
  • 3. Re: MVC for ActionListener
    TPD-Opitz-Consulting-com Expert
    Currently Being Moderated
    Hunter_wow wrote:{quotev
    Ok, thanks. Tried to put the Listener into a Model-package but I then get cyclic dependencie for view->model->controller->view .... I guess it is expected and not possible to solve?
    What you have so fahr is a View (your GUI class/Button) and a Controller (your ActionListener)
    What you are missing is the Model.
    It is not enough to create a model package and put random classes there...
    You need (at least) one more class representing the data your Application is working on. Then the Model defines Listener interfaces and provides <tt>addListener()</tt> methods used by your GUI elements to get updated on data changes. It also provides data manipulation methods to be called by the Controller.

    If you do it right you'll end up with straight dependencies:
    View depends on Controller and Model
    - "display type" elements like Lables become listeners at the Model
    - and "action type" elements like buttons trigger Controller objects
    Controller depends on Model only.
    The Model depends on neither one of the other.

    In real life usually view and controller are mixed somehow.
    But the Model (that you don't have so fahr) is always separated.

    bye
    TPD

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points