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

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: