Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Dec 5, 2000

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();
    }
}
Teaw
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap