简体   繁体   中英

Model-view-control and swing gui

I've a doubt. I don't know where insert each eventlistener in a pattern MVC. Is it right to insert them in a controller or is better insert eventlistener directly in view?And from view eventlistener can call a controller to do something.

Your event listeners should be in the controller. The controller holds an instance of the view and your view has public methods to set the event listeners of the GUI controls(JTextField etc).

Example: You have a view that has a JButton control called buttonSubmit and you want to listen for when someone interacts with that button.

View

public void addSubmitButtonListener(ActionListener listener) {
    buttonSubmit.addActionListener(listener);
}

Controller

public void run() {
    view.addSubmitButtonListener( new SubmitButtonListener() );
}

class SubmitButtonListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent evt) {
        // What happens after someone interacts with the button goes in here.
    }

}

That SubmitButtonListener class goes directly into the controller as an inner class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM