How to use Trees in Java?
Hello friends,
I am new to this forum, so kindly ignore my mistakes. I have done some basic programs in Java. Now I want to give a hierarchical data look to the user. Its just same like the one that we use in Windows Explorer. Later I came to know that the trees function can do this thing.! But I don't know how to use it. So can anyone please tell me how to use Trees in Java.?? Hoping that someone would help me soon.!!
Re: How to use Trees in Java?
A control that displays a set of hierarchical data as an outline. If you want to display hierarchical data in Java, then you would have to use JTree class. You should know that there is no data in the JTree object, it only provides a view of the data. You can identify a specific node in a tree by TreePath. You can also identify that by the row, because each row in the display area displays one node. Since you are new you should not be knowing the node.!! Each row contains exactly one item of data which can be known as node. Every tree has a root node from which all nodes descend.
Re: How to use Trees in Java?
You will have to create a TreeNode while initializing a tree. And if you want to make node a leaf, then you would have to invoke setAllowsChildren(false). A node can either have children or not. Leaf nodes are the nodes that can't have children. While branch nodes can have any number of children. I think that once you understand the concept of the Tree you can do the coding for the same. Hope that you would have got the basic points.
Re: How to use Trees in Java?
The following sample of a code will help you for creating the JTree object :
Code:
DefaultMutableTreeNode top = new DefaultMutableTreeNode("This is Trial of Tree");
createNodes(top);
final JTree tree = new JTree(top);
...
JScrollPane treeView = new JScrollPane(tree);
Re: How to use Trees in Java?
Once you start using the tree, there are many times when you would have to creates the nodes under the root node. I thought that providing the code for same would be helpful. So here is the code for creating the nodes under the root node :
Code:
private void createNodes(DefaultMutableTreeNode top) {
DefaultMutableTreeNode category = null;
DefaultMutableTreeNode book = null;
category = new DefaultMutableTreeNode("Names of Cars");
top.add(category);
car = new DefaultMutableTreeNode(new carInfo
("Mustang.html"));
category.add(car);
car = new DefaultMutableTreeNode(new carInfo
("Lamborghini Diablo.html"));
category.add(car);
car = new DefaultMutableTreeNode(new carInfo
("Acura.html"));
category.add(car);
category = new DefaultMutableTreeNode("Cars for Fans");
top.add(category);
car = new DefaultMutableTreeNode(new carInfo
("Information about Cars",
"vm.html"));
category.add(car);
car = new DefaultMutableTreeNode(new carInfo
("Information about Cars",
"inf.html"));
category.add(car);
}