2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. The main thing in MVC is separating the presentation from the business logic and domain. It's really not a trivial issue, since many many articles have been written about it. You can find some bits in Martin Fowler's "Refactoring" etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.