jtree in java

In Java, JTree is a Swing component that provides a hierarchical view of data. It is used to display data in a tree structure, with nodes that can be expanded or collapsed to show or hide child nodes. JTree is typically used to display file system hierarchies, organization charts, and other kinds of hierarchical data.

Here is an example of how to create and display a simple JTree:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class JTreeExample {
    public static void main(String[] args) {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
        DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");
        DefaultMutableTreeNode child3 = new DefaultMutableTreeNode("Child 3");

        root.add(child1);
        root.add(child2);
        child2.add(child3);

        JTree tree = new JTree(root);
        JFrame frame = new JFrame("JTree Example");
        frame.add(new JScrollPane(tree));
        frame.setSize(200, 200);
        frame.setVisible(true);
    }
}
S‮ecruo‬:www.theitroad.com

In this example, we create a DefaultMutableTreeNode to represent the root node of the tree, and then create several child nodes using DefaultMutableTreeNode. We add the child nodes to the root node using the add() method. We then create a JTree using the root node, and add it to a JScrollPane which is added to a JFrame.

The resulting JTree will display the tree structure with the root node at the top, and the child nodes below it. The child nodes can be expanded or collapsed by clicking on the plus or minus sign next to the node.