Set Color of Tree Nodes

Set Color of Tree Nodes

Using Swing, you can set the color of each node in Jtree. This is done by customizing your own TreeCellRenderer (overriding the DefaultTreeCellRenderer class), then calling the setBackgroundSelectionColor() method of DefaultTreeCellRenderer.

 import java.awt.*;import javax.swing.*;import javax.swing.tree.*;public class ColoredTree{    public static void main(String[] args)    {        JFrame frame = new JFrame();        JTree tree = new JTree();        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.getContentPane().add(tree, BorderLayout.CENTER);        tree.setCellRenderer(new DefaultTreeCellRenderer()        {             public Component getTreeCellRendererComponent(JTree pTree,                 Object pValue, boolean pIsSelected, boolean pIsExpanded,                 boolean pIsLeaf, int pRow, boolean pHasFocus)             {	    DefaultMutableTreeNode node = (DefaultMutableTreeNode)pValue;	    super.getTreeCellRendererComponent(pTree, pValue, pIsSelected,                     pIsExpanded, pIsLeaf, pRow, pHasFocus);                 if (node.isRoot())	       setBackgroundSelectionColor(;	    else if (node.getChildCount() > 0)	       setBackgroundSelectionColor(Color.yellow);	    else if (pIsLeaf)	       setBackgroundSelectionColor(;	    return (this);	}        });        frame.setSize(500, 500);        frame.pack();;    }}

See also  Monetize TikTok For Your Business

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist