简体   繁体   English

在Java swing MVC中传递模型对象以查看对象是一种好的设计模式吗?

[英]Is it good design pattern to pass model objects to view objects in java swing MVC?

I have class Model : 我有班级Model

class Model {
Object[][] objects=new Object[3][];
}

I have a controller which is action listener: 我有一个控制器,它是动作侦听器:

class MyListener implements ActionListener {
   public void actionPerformed(ActionEvent a){
          //here I have to get objects array from Model and pass it to view to display
}
}

But I worry if I pass objects array to JPanel it will cause problems later. 但是我担心如果将对象数组传递给JPanel会在以后引起问题。

Is there another way for JPanel to use objects ? JPanel还有另一种使用objects吗?

Haven't touched Swing for a very long time, but still: JPanel doesn't really need any kind of model objects, it's just a widget that can aggregate other widgets. 接触Swing已有很长时间了,但是仍然:JPanel确实不需要任何模型对象,它只是一个可以聚合其他小部件的小部件。 Usually, it makes sense to pass the model to widgets that can actually show something, for instance, textArea, textField, tables and so on. 通常,将模型传递给实际上可以显示某些内容的小部件是有意义的,例如,textArea,textField,表等。

In an MVC model implementation of swing, Components act as both as a view (obviously) and controllers by means of listeners reacting to some events. 在SVC的MVC模型实现中,组件(通过显然对侦听器的响应)充当视图(显然)和控制器的角色。

In any case, the following rules apply: 无论如何,以下规则适用:

  • Controllers change the model 控制器改变模型
  • Views are "subscribed" to the model changes. 视图已“订阅”到模型更改。 Usually, its implemented in internal models of components in swing itself, but you can extend them and define your behavior. 通常,它是在swing本身的组件内部模型中实现的,但是您可以扩展它们并定义行为。 Once model gets changed by controller, it fires special events to views, like "hey, I'm changed". 一旦控制器更改了模型,它将向视图触发特殊事件,例如“嘿,我被改变了”。
  • Model is usually loosely coupled to views. 模型通常与视图松散耦合。
  • Views react to these events and apply the changes (usually repainting with new data). 视图对这些事件做出反应并应用更改(通常使用新数据重新绘制)。

From your question its kind of hard to tell what will happen when someone changes the model (not enough information). 从您的问题中很难判断出当有人更改模型时会发生什么(信息不足)。

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

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