开发者

Java Swing - Should JTree be used with TreeModel - MVC design pattern

开发者 https://www.devze.com 2022-12-23 01:44 出处:网络
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 JCompo

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开发者_如何学JAVA 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?


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, ...)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消