What is the controller in Java Swing?

前端 未结 7 801
不知归路
不知归路 2020-12-23 10:38

I would like to apply the MVC design to my Java application using Swing in a meaningful way. Therefore my question is, how the controllers would be structured in Java Swing?

7条回答
  •  攒了一身酷
    2020-12-23 11:33

    For a clear separation of View and Controller, you could do it like this:

    public class MyView extends SomeSwingComponent {
    
       private Controller controller;
       public View(Controller controller) {
         this.controller = controller;
         JButton saveButton = new JButton("Save");
         button.addActionListner(controller.getSaveButtonListener());
       }
    }
    

    public class MyController implements Controller {
      private ActionListener saveButtonListener;
      @Override
      public ActionListener getSaveButtonListener() {
        if (saveButtonListener == null) {
          saveButtonListener = new ActionListener() {
            // ...
          }
      }
    }
    

    Now we could implement different controllers which could be convenient, if we want to use the view component with different models. The controller is a strategy of the actual view instance.

    In most cases it is just enough to define listeners as anonymous classes, because they usually just call a method on the controller instance. I use listeners usually as simple dispatchers - they receive a notification and send a message to another object. A listener class should implement too much business logic, that's beyond its responsibilties.

提交回复
热议问题