使用 Swing 实现 Java SE MVC [英] Java SE MVC implementation with Swing
问题描述
我已经使用 PropertyChageSupport
和 PropertyChageListener
为带有 Swing 的 Java SE 实现了 MVC 模式.MVC的实现图如下.
I've implemented MVC pattern for Java SE with Swing using PropertyChageSupport
and PropertyChageListener
. The diagram for implemented MVC is as follows.
在View
的实现中,我在Controller
的帮助下对Model
中的属性进行了修改.
In the implementation of View
, I do property change in Model
with the help of Controller
.
View
包含如下所示的 Ok 按钮代码.
View
contains code like following for Ok button.
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
modelController.setNumber(Integer.parseInt(numberField
.getText()));
modelController.setName(nameField.getText());
}
});
完整代码可以在 SwingMVC 中找到.
Complete code can be found in SwingMVC.
现在,我的问题是,我应该在 View
中为 btnOk
编写上述代码,还是应该在 Controller
中的方法中编写它?code> 以便在 View
中,我会做
Now, My question is, Do I write above code for btnOk
in View
or Should I write it in a method in Controller
so that in View
, I'll be doing
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
modelController.btnOkActionPerformed();
}
});
以上两种实现方式中,MVC的首选实现方式是什么?
推荐答案
首先警告:我不是专业人士或学生,而是业余爱好者,但话虽如此,我个人更喜欢你的第二个例子,
First a caveat: I'm not a professional or student but a hobbiest, but having said that, my own preference is with your second example,
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
modelController.btnOkActionPerformed();
}
});
控件必须调用视图上的方法来提取信息,并且它调用的任何方法都将是视图实现的接口的一部分.我在这方面的目标是让视图尽可能保持愚蠢,并尽一切可能尽可能地松散耦合.
The control would have to call methods on the view to extract information, and any methods it would call would be part of an interface that the view implements. My goal in this is to keep the view as dumb as possible and do almost anything to loosen coupling as much as possible.
这篇关于使用 Swing 实现 Java SE MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!