Java Swing - JTree 是否应该与 TreeModel 一起使用 - MVC 设计模式
我将在我的 Java Swing 桌面应用程序中使用 JTree。我阅读了 MVC 设计模式
,根据它,我们应该使用 Swing Components
的 Model
类来分离 JComponent 的数据模型
来自其演示部分。
所以我的快速问题如下:
JTree(TreeModel newModel)
JTree(Object[]值)
JTree(TreeNode root)
JTree(Vector值)
JTree(HashTable value)
以上用于创建 JTree< 的选项/代码>,
Q1。使用 JTree(TreeModel newModel) 来应用 MVC 模式是否总是更好?
I am going to use JTree
in my Java Swing Desktop Application. I read about MVC Design pattern
and according to it, we should use Model
classes of Swing Components
to separate the datamodel of a JComponent
from its presentation part.
So my quick question is as follows:
JTree(TreeModel newModel)
JTree(Object[] value)
JTree(TreeNode root)
JTree(Vector<?> value)
JTree(HashTable<?, ?> value)
Out of the above options for creating a JTree
,
Q1. Is it always better to go with JTree(TreeModel newModel)
to apply the MVC
pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于您的需求。我倾向于认为将非模型对象作为输入的 Swing 组件构造函数实际上是快速原型设计的快捷方式。事实上,在幕后,Swing 组件将从输入对象创建一个模型,因为它需要一个模型对象来正确发送所有事件。
因此,我的建议是:
It depends upon your needs. I tend to think Swing components constructors taking as input non-model objects are in fact shortcuts for fast prototyping. indeed, behind the hoods, the Swing component will create a model from the input object, since it requires a model object to have all the events correctly sent.
As a consequence, here is my advice :
正如 Riduidel 所说,JTree 始终在内部使用 TreeModel,因此其他构造函数实际上只是为了方便。
还有 setModel(JTree) 方法,它将设置(和替换)模型。在一个重要的应用程序中,您可能需要在填充数据之前构建框架及其组件。
我不认为任何构造函数是非 MVC 的。在这方面更重要的是让负责数据、UI 和逻辑的代码尽可能独立且不依赖。这使您可以更好地对代码进行单元测试,并有助于提高灵活性和可重用性。
As Riduidel said, JTree always uses a TreeModel internally, so the other constructors are really just for convenience.
There's also the setModel(JTree) method, which will set (and replace) the model. In a non-trivial application you'll probably want to build the frame and it's components before filling in the data.
I don't consider any of the constructors as being non-MVC. What's more important in that regard is that you keep code responsible for the data, UI, and logic as separate and non-dependent as possible. That allows you to better unit test your code, and it helps with flexibility and re-usability.