How to change the background color of an element in the tree view?

Answered

Hi Communitiy,

I use a ColoredTreeCellRender to render a Tree. Now I would like to change the background color of one of its elements.
I tried to use the setBackground() method, but it does change nothing, that I see. I also experimented with the opaque.

What I'm doing wrong?

Markus

0
5 comments

Hi Markus,

The SimpleTextAttributes object you pass as a parameter to the append() method has a bgColor attribute. Please make sure that you're setting it correctly.

0

I set it like this:

SimpleTextAttributes simpleTextAttributes = new SimpleTextAttributes(Color.green, Color.black, null, SimpleTextAttributes.STYLE_PLAIN);
this.append(psiClass.getName(), simpleTextAttributes);


the result is this:
TreeView.jpg

The PsiClasses that are marked with the JUnit marker should be highlighted with a green background.
I just don't see my mistake. ?:|

Markus

0

Hi,

did you ever solved this ? When I do the same, then tree cell background is correct only when its outside of the tree itself. Like when ToolWindow is too thin and on hover cell is rendered over gutter.

0

To have background colour you need to specify opaque style via SimpleTextAttributes.STYLE_OPAQUE in addition to non-null background colour.

The project view tree has a few more quirks and you also need to provide a non-null forcedForeground colour or the background will be ignored because SimpleTextAttribute toTextAttributes always uses null for background colour and this method is used to combine forcedForeground colour with other attributes.

 

0

Thank you Vladimir, it really works. But I find out, that what I really needed was "file colors" feature, since I want whole row to have same background, not just "label" of the tree node.

If anyone will be looking for the same, then you need to extend Tree and override its two methods isFileColorsEnabled() to return true and getFileColorForPath() to return proper color or null for each path. Or alternatively you can override getFileColorFor(Object) where Object is "user object" within DefaultMutableTreeNode.

Probably the most simple solution is to have your "user objects" implement ColoredItem interface, since DefaultTreeUI will use it to draw the background.

0

Please sign in to leave a comment.