[英]Java Swing MVC architecture
如何组织Java Swing应用程序来实现MVC架构?
请参阅: Swing架构概述
i would categorize my classes: 我会把我的课分类:
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.