Creating a JTree Component
In this section, you will learn about the JTree and its components as well as how to create an JTree component. Here, first of all we are going to describe about the JTree and its component. The java.swing package provides the JTree and its component.
JTree: The tree is a special type of graph that designed for displaying data with the hierarchical properties by adding nodes to nodes and keeps the concept of parent and child node.
Node: A node is an object at any position within the JTree where the data are associated or being represented.
Path: The path is the collection of contiguous set of nodes that contains one or many nodes. The path is empty or null when the path has not any node.
Leaf: This is a special types of node at the end of a path. The leaf node has not connected to more nodes.
Root: This is the node of highest point within the hierarchy in tree.
Parent: It represents the relationship of node with another node. In object-oriented programming concepts the parent is a super class.
Child: It represents the relationship of node with another node. In object-oriented programming concepts the child is a subclass of its parent. It inherits all properties of its parent.
Description of program:
The following program creates the simple JTree component. The tree is a special type of graph that build the tree hierarchy by adding nodes to nodes and keeps the concept of parent and child node or root and a child of root node. Whenever you will go to create a tree, you will need root node that will be created by the DefaultMutableTreeNode() method. All objects of DefaultMutableTreeNode are added in the specifying parent or child nodes that will be specified by you and root node are added in the JTree object that will also added on the frame.
Description of code:
DefaultMutableTreeNode("Color", true):
This is the constructor of DefaultMutableTreeNode class. It creates a tree
node with no root node, the child of root node, specified by user object and it
allows only children that have to be specified. It takes boolean types values
either 'true' or 'false'. If you will take 'true' that means children
node are allowed otherwise it will display the IllegalStateException.
JTree(TreeNode parent):
This is the constructor of JTree class that shows a set of hierarchical
data. It returns a JTree with given TreeNode that displays the root node
in a tree. By default, the tree defines the leaf node of a tree. It takes
the following types of arguments:
parent: This is the name of an object of TreeNode that displays the root node.
Here is the code of program:
import javax.swing.*;
|
Output of program:
![]() |