tags:

views:

139

answers:

2

I created a tree but i'm unaware of setting color to it.

    JTree tree;
    JList list;
    JFrame frame;
    tree=new JTree("Tree");
    frame.add(tree,BorderLayout.WEST);
    tree.addTreeSelectionListener(this);
    frame.add(teamMember,BorderLayout.NORTH);
    frame.add(list,BorderLayout.CENTER);

Is possible to set color in JTree?

A: 

JTree inherits color methods from JComponent, e.g. setBackground. See for example here

Frank
A: 

The colors (both foreground and background) for your tree nodes come from the TreeCellRenderer that is associated with your JTree. The tree cell renderer for your JTree depends on the look and feel, but you can probably assume that it is descended from DefaultTreeCellRenderer. If it is, then you can call several color-setting methods on DefaultTreeCellRenderer to change the colors of your tree, like this:

tree = new JTree(root);
if (tree.getCellRenderer() instanceof DefaultTreeCellRenderer)
{
    final DefaultTreeCellRenderer renderer = 
        (DefaultTreeCellRenderer)(tree.getCellRenderer());
    renderer.setBackgroundNonSelectionColor(Color.YELLOW);
    renderer.setBackgroundSelectionColor(Color.ORANGE);
    renderer.setTextNonSelectionColor(Color.RED);
    renderer.setTextSelectionColor(Color.BLUE);
}
else
{
    System.err.println("Sorry, no special colors today.");
}
Joe Carnahan
Note that executing this sample code may hurt your eyes due to all of the clashing yellow, orange, and red colors. ;-)
Joe Carnahan