简体   繁体   English

Java Swing MVC架构

[英]Java Swing MVC architecture

如何组织Java Swing应用程序来实现MVC架构?

请参阅: Swing架构概述

i would categorize my classes: 我会把我的课分类:

  • object classes: to represent objects 对象类:表示对象
  • functionality classes: to provide functionality. 功能类:提供功能。 for instance, methods to read/write files or methods to make calculations possibly using some object classes 例如,读取/写入文件的方法或可能使用某些对象类进行计算的方法
  • and GUI classes (using Swing) which will be what the user will see. 和GUI类(使用Swing),这将是用户将看到的。 these classes will do what the functionality classes provide. 这些类将执行功能类提供的功能。

Your project must be consist at least of three entities: your model , your view and yor controller .Your model represents your data, view is a view for your data and controller is something that creates both view and controller. 您的项目必须至少由三个实体组成:您的model ,您的view和您的controller您的模型代表您的数据,视图是您的数据的视图,控制器是创建视图和控制器的东西。

Let's suppose you've a rectangle and want to build a GUI that shows the area of the rectangle when user types its side. 假设您有一个矩形,并且想要构建一个GUI,当用户键入其边时,该GUI显示矩形的区域。

Your model must extends Observable class, in this way you mark class Square as model in your MCV architecture . 您的模型必须扩展Observable类,这样您就可以将类Square标记为MCV architecture模型。

public class Square extends Observable {ecc....}

when you set the side, you have to set the state of the model as changed and notify observers which are listening on your model, such as: 设置侧面时,必须将模型的状态设置为已更改,并通知正在侦听模型的观察者,例如:

public void setSide(double side) {
  this.side=side;
  setChanged();
  notifyObservers();
}

PS: setChanged() and notifyObservers() are provided by Observable class. PS: setChanged()notifyObservers()Observable类提供。

Now the second step, your View must implement Observer interface, so you mark this as listener for model's change. 现在第二步,您的View必须实现Observer接口,因此您将此标记为模型更改的侦听器。 Implementing Observer forces you to write update method. 实现Observer强制您编写update方法。

public class Square_View implements Observer {
    JLabel area;
    ......
    @Overried
    public void update (Observable o, Object arg1) {
        Square square=(Square)o;
        area.setText(square.getArea());
    }

Well, as soon as your square's side changes, a notification is triggered and update method is invoked. 好吧,只要方块的一侧发生变化,就会触发通知并调用update方法。

Now the controller , the mind of MVC architecture: 现在controller ,MVC架构的思想:

public class MyProgram extends JFrame {
      ... somewhere in your class
      Square s=new Square();
      Square_View sv=new Square_View();
      s.addObserver(sv);
}

As I said before, you create both model and view and register the view as observer for your model. 正如我之前所说,您创建模型和视图,并将视图注册为模型的观察者。

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

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