I was working in the same application where I found the previous quirk. This time I tried to make a cell renderer put a background color in the cell, to no avail. I even tried to explicitly return a JLabel as the cell renderer, with the proper background color set. Nothing.

The answer to the mystery is the fact that JLabel is transparent by default, transparent components don't render their background, and DefaultTreeCellRenderer extends JLabel.

After some googling again I found out that I'm not alone. There is even a bug raised, and closed as "not a bug". From the JComponent.setOpaque() javadocs:

    /**
* If true the component paints every pixel within its bounds.
* Otherwise, the component may not paint some or all of its
* pixels, allowing the underlying pixels to show through.
*


* The default value of this property is false for JComponent.
* However, the default value for this property on most standard
* JComponent subclasses (such as JButton and
* JTree) is look-and-feel dependent.
*
* @param isOpaque true if this component should be opaque
* @see #isOpaque
* @beaninfo
* bound: true
* expert: true
* description: The component's opacity
*/

The workaround? Add this.setOpaque(true) in the overriden getTreeCellRendererComponent() method:
public class BagroundColorEnabledRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row);
this.setOpaque(true);
return this;
}
}
Happy Coding!

No TrackBacks

TrackBack URL: http://tech.soronthar.com/mt/mt-tb.cgi/41

Leave a comment