简体   繁体   English

Java Swing-如何分离UI组件

[英]Java Swing - how to separate UI components

I have two UI components as follows: 我有两个UI组件,如下所示:

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. 这里的问题是在UIPanel类中,我想添加一个ActionListener,它将使用Model来决定如何处理用户动作。 Unfortunately I decided to split the two classes and I do not have access to Model directly. 不幸的是,我决定将这两个类分开,而且我无法直接访问Model。 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. 一个明显的解决方案是将UIPanel类简单地粘贴在MainPanel中,但是我在考虑是否有办法保持拆分。

You could simply give UIPanel a reference to the Model : 您可以简单地给UIPanel提供对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? 也许MainPanel根本不需要引用Model

Sounds like you need to add a controller class (to make it more like MVC). 听起来您需要添加一个控制器类(使其更像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. 因此,它是控制器,它从UI侦听用户事件并决定如何处理它。

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. 我个人将只有一个控制器用于一个视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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