How do I remove JTree default icons?

You can remove JTree default icons by modifying the tree cell renderer object. To get the cell renderer call the JTree.getCellRenderer() which will return a DefaultTreeCellRenderer object. Then you can remove the icon by setting a null value to the setLeafIcon(), setClosedIcon() and setOpenIcon().

package org.kodejava.swing;

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

public class JTreeRemoveIcon extends JFrame {
    public JTreeRemoveIcon() throws HeadlessException {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new JTreeRemoveIcon().setVisible(true));
    }

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Address Book");
        DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
        DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
        DefaultMutableTreeNode c = new DefaultMutableTreeNode("C");

        DefaultMutableTreeNode aContact = new DefaultMutableTreeNode("Alice");
        DefaultMutableTreeNode bContact = new DefaultMutableTreeNode("Bob");
        DefaultMutableTreeNode cContact = new DefaultMutableTreeNode("Carol");

        root.add(a);
        root.add(b);
        root.add(c);

        a.add(aContact);
        b.add(bContact);
        c.add(cContact);

        JTree tree = new JTree(root);

        // Remove default JTree icons
        DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
        renderer.setLeafIcon(null);
        renderer.setClosedIcon(null);
        renderer.setOpenIcon(null);

        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(200, 400));

        getContentPane().add(tree);
    }
}
Remove JTree Default Icon

Remove JTree Default Icon

How do I add selection listener to JTree?

This example shows you how to use the TreeSelectionListener to add a tree selection listener to the JTree component. In the listener method below you can see how to get the selected path and print out the selected path to the console.

package org.kodejava.swing;

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

public class JTreeSelectionListenerDemo extends JFrame {

    public JTreeSelectionListenerDemo() throws HeadlessException {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JTreeSelectionListenerDemo().setVisible(true));
    }

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode chapterOne = new DefaultMutableTreeNode("Chapter One");
        DefaultMutableTreeNode one = new DefaultMutableTreeNode("1.1");
        DefaultMutableTreeNode two = new DefaultMutableTreeNode("1.2");
        DefaultMutableTreeNode three = new DefaultMutableTreeNode("1.3");

        root.add(chapterOne);
        chapterOne.add(one);
        chapterOne.add(two);
        chapterOne.add(three);

        JTree tree = new JTree(root);
        tree.addTreeSelectionListener(e -> {
            TreePath path = e.getPath();
            int pathCount = path.getPathCount();

            for (int i = 0; i < pathCount; i++) {
                System.out.print(path.getPathComponent(i).toString());
                if (i + 1 != pathCount) {
                    System.out.print(" | ");
                }
            }
            System.out.println();
        });

        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(200, 400));

        getContentPane().add(pane);
    }
}

How do I change color of selected node in JTree?

This example show you how to change the color of the selected node of the JTree component. It shows you how to set the node background color, the font color and the selected node border color.

To do this you need to obtain the DefaultTreeCellRenderer object from the JTree instance and modified the selection color of the node.

package org.kodejava.swing;

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

public class JTreeTextSelectionColorDemo extends JFrame {
    public JTreeTextSelectionColorDemo() throws HeadlessException {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JTreeTextSelectionColorDemo().setVisible(true));
    }

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Department");
        DefaultMutableTreeNode book = new DefaultMutableTreeNode("Books");
        DefaultMutableTreeNode fiction = new DefaultMutableTreeNode("Fictions");
        DefaultMutableTreeNode science = new DefaultMutableTreeNode("Sciences");
        DefaultMutableTreeNode text = new DefaultMutableTreeNode("Text Books");
        DefaultMutableTreeNode children = new DefaultMutableTreeNode("Children");

        root.add(book);
        book.add(fiction);
        book.add(science);
        book.add(text);
        book.add(children);

        JTree tree = new JTree(root);

        // Get the DefaultTreeCellRenderer instance of the JTree
        // component. Then we customize the color of the selection
        // node using blue background, white font color and black
        // border.
        DefaultTreeCellRenderer renderer =
                (DefaultTreeCellRenderer) tree.getCellRenderer();
        renderer.setTextSelectionColor(Color.white);
        renderer.setBackgroundSelectionColor(Color.blue);
        renderer.setBorderSelectionColor(Color.red);

        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(250, 350));

        getContentPane().add(pane);
    }
}
JTree Node Color Demo

JTree Node Color Demo

How do I use a JTree component?

The example introduce you how to use the JTree swing component to create a presentation of hierarchical data. The hierarchical data can be viewed in expand mode or collapse mode.

To create an item of the tree we create an instance of DefaultMutableTreeNode which located in the javax.swing.tree package. This class implements the TreeNode and MutableTreeNode interfaces. Mutable means that the node can be changed. It can be added new children node or deleted children node from their parent node.

Below we create a tree component to display information about week day names and the month names. The Root node have the Days and Months. The Days node contains a week day names and the Months node contains the month names.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.text.DateFormatSymbols;

public class JTreeDemo extends JFrame {
    public JTreeDemo() {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new JTreeDemo().setVisible(true));
    }

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Creating tree node of day names.
        DefaultMutableTreeNode day = new DefaultMutableTreeNode("Days");
        DefaultMutableTreeNode sun = new DefaultMutableTreeNode("Sunday");
        DefaultMutableTreeNode mon = new DefaultMutableTreeNode("Monday");
        DefaultMutableTreeNode tue = new DefaultMutableTreeNode("Tuesday");
        DefaultMutableTreeNode wed = new DefaultMutableTreeNode("Wednesday");
        DefaultMutableTreeNode thu = new DefaultMutableTreeNode("Thursday");
        DefaultMutableTreeNode fri = new DefaultMutableTreeNode("Friday");
        DefaultMutableTreeNode sat = new DefaultMutableTreeNode("Saturday");

        // Adding the day nodes into day tree node.
        day.add(sun);
        day.add(mon);
        day.add(tue);
        day.add(wed);
        day.add(thu);
        day.add(fri);
        day.add(sat);

        // Creates tree node of month names using a for loop where the
        // month names is obtained using the DateFormatSymbols class.
        DefaultMutableTreeNode month = new DefaultMutableTreeNode("Months");
        String[] months = DateFormatSymbols.getInstance().getMonths();
        for (String monthName : months) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(monthName);
            month.add(node);
        }

        // Creating a root node for our JTree and add day and month items
        // to the tree.
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        root.add(day);
        root.add(month);

        // Creating an instance of JTree using the instance of
        // DefaultMutableTreeNode. We also create a scroll pane for our
        // tree container.
        JTree tree = new JTree(root);
        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(250, 450));
        getContentPane().add(pane);
    }
}
Swing JTree Demo

Swing JTree Demo