Derek
Derek

Reputation: 9943

Java: View (GUI) and Controllers Interaction with MVC?

How does one most efficiently connect a view and a controller in a MVC-esque Java application. Currently, I'm doing the following:

  1. Controller creates view and passes itself into the view as a parameter:

    MyView view = new MyView(this);

  2. View has ActionListeners for buttons. ActionListener doesn't do much but fire an action in the controller:

    private class ButtonAListener implements ActionListener
      {
    
          @Override
          public void actionPerformed(ActionEvent arg0) {
              controller.clickedButtonA();
          }
    
      }
    

It is working OK, but is this acceptable? For example, if a button is clicked in the view, the ActionListener passes that information into the controller, which does some calculations, and passes back a command to update the view.

Upvotes: 2

Views: 1681

Answers (1)

emesx
emesx

Reputation: 12755

IMHO it is acceptable. I think any solution is ok, as long as no tight coupling occurs. Depending what GUI library you are using (AWT,SWT, Swing..) different classes are appropriate though. Btw. you should check adapters out (if you dont know them already): http://blogs.oracle.com/CoreJavaTechTips/entry/listeners_vs_adapters

I'd recommend moving the creation of view from the controller. If view and controller are to separated (and that's the whole point), the controller should only have a setter method (or other dependency injection mechanisms). I think you should have a launcher class that creates the controller and views and then connects them together.

Upvotes: 2

Related Questions