This is a Java Program to Create a JTree with a Root Node and Other Nodes Spanning from Root Node
We have to write a program in Java such that it creates a tree with a root node and nodes spanning from it.
For creating a JTree, we can have the following set of input and output.
To create a tree:
On the execution of the program, it is expected that the tree is created and displayed on the frame.
1. Create a root node ‘A’.
2. Create nodes ‘B’ and ‘C’, and add them to their parent node ‘A’.
3. Create node ‘D’, and add it to its parent node ‘B’.
4. Create nodes ‘E’ and ‘F’, and add them to their parent node ‘C’.
5. Create a tree with the root node ‘A’, and add the tree to frame.
6. Display the frame.
Here is source code of the Java Program to create a tree using JTree. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.
/* Java Program to create a tree*/
public static void main(String args)
//Create a frame
JFrame frame = new JFrame("Tree");
//Create root 'A'
DefaultMutableTreeNode A=new DefaultMutableTreeNode("A");
//Create children 'B' & 'C'
DefaultMutableTreeNode B=new DefaultMutableTreeNode("B");
DefaultMutableTreeNode C=new DefaultMutableTreeNode("C");
//Create child 'D' of B
DefaultMutableTreeNode D=new DefaultMutableTreeNode("D");
//Create children 'E' and 'F' of C
DefaultMutableTreeNode E=new DefaultMutableTreeNode("E");
DefaultMutableTreeNode F=new DefaultMutableTreeNode("F");
//Create a tree
JTree tree=new JTree(A);
//Display the frame
1. To create a node use the DefaultMutuableTreeNode class.
2. To create a tree use JTree class and specify the root node of the tree.
Here’s the run time test case for creating a tree using JTree.
Sanfoundry Global Education & Learning Series – Java Programs.Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!