JTree and Tree Models - potatoscript/JavaSwing GitHub Wiki

πŸ“‘ JTree and Tree Models in Java Swing 🌳


πŸ“ What is JTree?

In Java Swing, JTree is a component used to display a hierarchical tree structure. It is commonly used to represent files, folders, organizational charts, and more. The tree consists of nodes, which can be expanded or collapsed to show or hide their child nodes.

Key Features:

  • Hierarchical Structure: Useful for displaying data in a tree structure (parent-child relationships).
  • Expandable Nodes: Allows users to expand or collapse nodes to view nested data.
  • Interactive: Can be customized with event listeners to interact with the tree.

βœ… How Does JTree Work?

  • Root Node: The topmost node of the tree.
  • Child Nodes: Nodes connected under the root or other nodes in the tree.
  • Model: The underlying structure that holds the tree data.

πŸ“š Step 1: Simple JTree Example

Let’s create a basic JTree with a root node and some child nodes.


πŸ“ Example: Basic JTree

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class JTreeExample {
    public static void main(String[] args) {
        // Create the root node
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

        // Create child nodes
        DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
        DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");

        // Add child nodes to the root
        root.add(child1);
        root.add(child2);

        // Create a JTree with the root node
        JTree tree = new JTree(root);

        // Set up the frame
        JFrame frame = new JFrame("JTree Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        
        // Add the tree to the frame
        frame.add(new JScrollPane(tree));

        // Display the frame
        frame.setVisible(true);
    }
}

🎨 Explanation

  • DefaultMutableTreeNode: This represents a single node in the tree. Each node can have multiple child nodes.
  • JTree: The component that displays the tree. We create it using the root node and its children.
  • JScrollPane: We wrap the JTree in a JScrollPane to enable scrolling when the tree is too large to fit on the screen.

πŸ‘©β€πŸŽ¨ Output:

When you run this code, you'll see a window with a simple tree structure that has a root and two child nodes. You can expand and collapse the nodes.


πŸ“š Step 2: Tree Models and Customizing the JTree

A TreeModel represents the data structure behind the tree. In this step, we will modify the tree’s behavior by using a custom TreeModel.


πŸ“ Example: Custom TreeModel

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;

public class CustomTreeModelExample {
    public static void main(String[] args) {
        // Create the root node
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

        // Create child nodes
        DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
        DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");

        // Add child nodes to the root
        root.add(child1);
        root.add(child2);

        // Create a TreeModel using the root node
        TreeModel treeModel = new DefaultTreeModel(root);

        // Create a JTree with the custom TreeModel
        JTree tree = new JTree(treeModel);

        // Set up the frame
        JFrame frame = new JFrame("Custom TreeModel Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);

        // Add the tree to the frame
        frame.add(new JScrollPane(tree));

        // Display the frame
        frame.setVisible(true);
    }
}

🎨 Explanation

  • Custom TreeModel: We created a TreeModel using DefaultTreeModel with the root node. This allows for more control over the data structure.
  • JTree: The tree is constructed using the custom tree model, which can be easily modified to hold different kinds of data.

πŸ‘©β€πŸŽ¨ Output:

You will see the same tree structure as before, but this time it is powered by a custom model that could be easily extended for more advanced use cases.


πŸ“š Step 3: Adding Icons to Nodes

Now, let's add icons to the tree nodes. You can customize each node with a different icon to make the tree visually appealing.


πŸ“ Example: JTree with Icons

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;

public class JTreeWithIconsExample {
    public static void main(String[] args) {
        // Create the root node
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

        // Create child nodes
        DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
        DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");

        // Add child nodes to the root
        root.add(child1);
        root.add(child2);

        // Set icons for the nodes (Using basic icons for demonstration)
        ImageIcon folderIcon = new ImageIcon("folder-icon.png"); // Replace with actual path to your icon
        ImageIcon fileIcon = new ImageIcon("file-icon.png"); // Replace with actual path to your icon

        // Set icons to each node
        child1.setUserObject(new DefaultMutableTreeNode("Child 1", folderIcon));
        child2.setUserObject(new DefaultMutableTreeNode("Child 2", fileIcon));

        // Create a TreeModel with custom icons
        TreeModel treeModel = new DefaultTreeModel(root);

        // Create a JTree with the custom TreeModel
        JTree tree = new JTree(treeModel);

        // Set up the frame
        JFrame frame = new JFrame("JTree with Icons Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);

        // Add the tree to the frame
        frame.add(new JScrollPane(tree));

        // Display the frame
        frame.setVisible(true);
    }
}

🎨 Explanation

  • Icons: We used ImageIcon to add custom icons to each node. You can replace "folder-icon.png" and "file-icon.png" with the actual paths to your icons.
  • Custom Nodes: The tree nodes are now represented with both text and images (icons).

πŸ‘©β€πŸŽ¨ Output:

When you run this, you’ll see a tree where each node has its own custom icon alongside the text. The tree will still have the same expandable and collapsible functionality.


πŸ“š Step 4: Handling Tree Events (Node Selection)

Now, let’s handle some basic events for the tree. For instance, when a node is selected, we can display information about the selected node.


πŸ“ Example: Tree Selection Listener

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class TreeSelectionListenerExample {
    public static void main(String[] args) {
        // Create the root node
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

        // Create child nodes
        DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
        DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");

        // Add child nodes to the root
        root.add(child1);
        root.add(child2);

        // Create a TreeModel
        DefaultTreeModel treeModel = new DefaultTreeModel(root);

        // Create the JTree
        JTree tree = new JTree(treeModel);

        // Add a listener to handle node selection
        tree.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent event) {
                // Get the selected node
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)
                        tree.getLastSelectedPathComponent();
                if (selectedNode != null) {
                    // Print the selected node's text
                    System.out.println("Selected Node: " + selectedNode.toString());
                }
            }
        });

        // Set up the frame
        JFrame frame = new JFrame("Tree Selection Listener Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);

        // Add the tree to the frame
        frame.add(new JScrollPane(tree));

        // Display the frame
        frame.setVisible(true);
    }
}

🎨 Explanation

  • Tree Selection Listener: We added a TreeSelectionListener to the JTree to listen for changes in the selected node.
  • Display Node Info: When a user selects a node, we print the selected node’s text to the console.

πŸ‘©β€πŸŽ¨ Output:

In the console, whenever a node is selected, its text is printed. You can expand this to show additional information or trigger other actions when a node is selected.