Java Swing - JTree 是否应该与 TreeModel 一起使用 - MVC 设计模式

发布于 2024-08-24 21:55:47 字数 585 浏览 7 评论 0原文

我将在我的 Java Swing 桌面应用程序中使用 JTree。我阅读了 MVC 设计模式,根据它,我们应该使用 Swing ComponentsModel 类来分离 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

渔村楼浪 2024-08-31 21:55:48

这取决于您的需求。我倾向于认为将非模型对象作为输入的 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 :

  • For a fast prototype, you may consider the use of these "mock-like" constructors
  • For a "real-world" application, don't even think about them, since sooner or latter will arise the need for specific event sending (to change one node rendering, making the tree grow, ...)
叹倦 2024-08-31 21:55:48

正如 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文