Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Create JTree Using Swing in Java?

Create JTree in Java

Condition for Creating JTree Using Swing in Java

  • Description: To create a JTree in Java using Swing, the `JTree` class from the swing package is used. First, a `DefaultMutableTreeNode` is created to represent the root of the tree. Child nodes are also instances of `DefaultMutableTreeNode` and are added to the root node to establish the tree hierarchy. Once the tree structure is defined, a `JTree` object is instantiated using the root node, which is passed to the constructor. The tree is then placed in a `JScrollPane` to provide scrolling functionality when the tree exceeds the available view area. The JTree can be customized with various features, including node selection, event listeners, and custom renderers for displaying nodes. Finally, the tree is added to a `JFrame` or another container for display on the GUI.
Sample Source Code
  • # JTreeExample.java
    package JavaSamples2;

    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 nodeA = new DefaultMutableTreeNode("JTree 1");
    DefaultMutableTreeNode nodeB = new DefaultMutableTreeNode("JTree 2");
    DefaultMutableTreeNode nodeC = new DefaultMutableTreeNode("JTree 3");

    root.add(nodeA);
    root.add(nodeB);
    root.add(nodeC);

    nodeA.add(new DefaultMutableTreeNode("JTree 1.1"));
    nodeA.add(new DefaultMutableTreeNode("JTree 1.2"));
    nodeB.add(new DefaultMutableTreeNode("JTree 2.1"));

    JTree tree = new JTree(root);

    JScrollPane treeScrollPane = new JScrollPane(tree);

    JFrame frame = new JFrame("JTree Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.add(treeScrollPane);
    frame.setVisible(true);
    }
    }
Screenshots
  • STEP 1: The JTree with root and child nodes will be displayed in the window.
  • The JTree with root and child nodes will be displayed in the window.