devxlogo

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(Color.red);	    else if (node.getChildCount() > 0)	       setBackgroundSelectionColor(Color.yellow);	    else if (pIsLeaf)	       setBackgroundSelectionColor(Color.green);	    return (this);	}        });        frame.setSize(500, 500);        frame.pack();        frame.show();    }}

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Seasoned Architects Evaluate New Tech

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.