简体   繁体   中英

Java Swing - how to separate UI components

I have two UI components as follows:

class UIPanel extends JPanel{ ... }

class MainPanel { Model m;
    //instantiates UIPanel }

Issue here is that in UIPanel class I would like to add an ActionListener that would use Model to make decisions on how to process user action. Unfortunately I decided to split the two classes and I do not have access to Model directly. An obvious solution is to simply stick the UIPanel class inside the MainPanel, but I was thinking whether there was a way to keep the split.

You could simply give UIPanel a reference to the Model :

class UIPanel {
    UIPanel(Model m) {
         m.addActionListener(listener);
    }
}

class MainPanel {
    ...
    MainPanel() {
        ...
        UIPanel uiPanel = new UIPanel(m); // Constructor, a separate setter would be possible also
        ...
     }
}

This obviously is a quite tight coupling. Maybe MainPanel does not need the reference to the Model at all?

Sounds like you need to add a controller class (to make it more like MVC). The view manipulation would be heard by the controller which would manipulate the model. The model would then fire an event saying it has changed and the view would listen. Upon receiving a notification the view would then update.

So it is the controller than listens to user events from the UI and decides what to do with it.

The model can then fire to more than one view. You could if you want have more than one controller acting on the same model (one for each view) or have on controller listening to events from each view. Personally I would have one controller for one view.

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