NickW
NickW

Reputation: 1343

MVC, and adding listeners to JPanels that are contained in other Componenets

I'm trying to implement MVC in my program, this is currently my Controller class:

public class Controller {

    private DatabaseModel model;
    private View view;

    public Controller(View view, DatabaseModel model){
        this.model = model;
        this.view = view;

        this.view.getMainPanel().getCandidateForm().
                  addSubmitListener(new CandidateListener());
    }

    class CandidateListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            System.out.println("ACTION");
        }
    }
}

because my view includes several private sub JPanels - MainFrame and CandidateForm - with the latter being where the button is, at line 10 i pass the candidateForm panel back up to the controller and then call it's 'addSubmitListener()' method, which adds the custom listener to the button.

does this seem like the correct way to add the listener? should i be defining the CandidateListener this way in the Controller? or maybe make an anonymous class in the sub JPanel?

Any other advice on best practice for MVC and listeners would also be appreciated!

Upvotes: 1

Views: 267

Answers (1)

trashgod
trashgod

Reputation: 205805

As noted here, "not every interaction needs to pass through your application's controller." Your approach is not wrong, but it may scale poorly. Consider using Action to encapsulate functionality, as suggested here. In a database context, this simple example creates an Action that adds a query result tab to a JTabbedPane. This more elaborate example uses a SwingWorker to query a database in the background; a corresponding Action might instantiate the worker and execute() it.

Upvotes: 1

Related Questions