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

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.