tags:

views:

188

answers:

2

Hi,

I want write custom TreeCellRenderer to have Root, nodes and leafs in different color.

This is my code:

tree.setCellRenderer(new DefaultTreeCellRenderer() {

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        {

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;

            if (node.isRoot()) {
                super.setBackground(Color.red);
            } else if (node.getChildCount() > 0) {
                super.setBackground(Color.yellow);
            } else if (leaf) {
                super.setBackground(Color.green);
            }
            return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);

        }

    }
});

Unfortunately only selected node changes color.

What am I doing wrong? TIA for help.

//update: I correlated my code, but it didn't help.

+4  A: 

Perhaps you mean setBackgroundColor() and not setBackgroundSelectionColor(), which, as its name suggests, only sets the color for the selected state.

Your use of super is superfluous [credit for this witty remark goes to Carl Smotricz].

Jonathan Feinberg
It's superfluous, even :)
Carl Smotricz
Ha ha ha ha ha ha
Jonathan Feinberg
Oops... I must drink more cofee and use notepad instead NetBeans. Thank You.
Maciek Sawicki
It doesn't work still :(.
Maciek Sawicki
OK it's setBackgroundNonSelectionColor().
Maciek Sawicki
A: 

Why do you call super.getTreeCellRendererComponent before you set the colors (and eventually return this) ? Try setting colors first and returning what super.getTreeCellRendererComponent returns

Dmitry