TreeModel creation

非 Y 不嫁゛ 提交于 2019-12-02 09:58:52

More sophisticated Swing components such as JTree, JTable, JList or JComboBox work with the concept of model. It means: the subjacent data that is being displayed by the component. They are designed in this way to have separate the data itself from their "visual" representation (a.k.a. the view) and allow the developer "forgot" (more or less) about data representation. So as explained in the tutorials, if you need to add a new data object to be displayed on one of these components you only have to add it to the model and the view will be automatically updated.

Having said this you'll see these components have a constructor that takes a model as argument:

These models are defined by interfaces which establish the basic contract that any concrete implementation must meet.

Particulalry in JTree's case we have the TreeModel interface and a default implementation: DefaultTreeModel. Additionaly any TreeModel has to work with node objects which have to implement the TreeNode interface.

So, to work with JTree you'll need a TreeModel and a bunch of TreeNodes related through a parent-child relationship. For instance something like this:

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Contacts"); // root node

DefaultMutableTreeNode contact1 = new DefaultMutableTreeNode("Contact # 1"); // level 1 node
DefaultMutableTreeNode nickName1 = new DefaultMutableTreeNode("drocktapiff"); // level 2 (leaf) node
contact1.add(nickName1); 

DefaultMutableTreeNode contact2 = new DefaultMutableTreeNode("Contact # 2");
DefaultMutableTreeNode nickName2 = new DefaultMutableTreeNode("dic19");        
contact2.add(nickName2);

root.add(contact1);
root.add(contact2);

DefaultTreeModel model = new DefaultTreeModel(root);
JTree tree = new JTree(model);

Picture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!