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.
Consider, we want to create the tree given below :
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*/
import javax.swing.*;
import java.awt.*;
import javax.swing.JTree;
import javax.swing.tree.*;
class Tree
{
//Driver function
public static void main(String args[])
{
//Create a frame
JFrame frame = new JFrame("Tree");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create root 'A'
DefaultMutableTreeNode A=new DefaultMutableTreeNode("A");
//Create children 'B' & 'C'
DefaultMutableTreeNode B=new DefaultMutableTreeNode("B");
DefaultMutableTreeNode C=new DefaultMutableTreeNode("C");
A.add(B);
A.add(C);
//Create child 'D' of B
DefaultMutableTreeNode D=new DefaultMutableTreeNode("D");
B.add(D);
//Create children 'E' and 'F' of C
DefaultMutableTreeNode E=new DefaultMutableTreeNode("E");
DefaultMutableTreeNode F=new DefaultMutableTreeNode("F");
C.add(E);
C.add(F);
//Create a tree
JTree tree=new JTree(A);
frame.add(tree);
//Display the frame
frame.setVisible(true);
}
}
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.
- Apply for Computer Science Internship
- Check Java Books
- Practice Information Technology MCQs
- Apply for Java Internship
- Practice BCA MCQs