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.example.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 {

    private void initializeUI() {
        setSize(150, 300);

        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");


        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();

        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(150, 300));


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JTreeTextSelectionColorDemo().setVisible(true);

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you šŸ™‚.

Leave a Reply

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