开发者

What's wrong with this colored JTree? (custom renderer problem)

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.


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].


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜