I've written a custom TreeCellRenderer in order to change a components appearance. Everything works fine, except that setBackground
has no effect. The code is definitely executed as the foreground color always changes correctly. Since selected items are rendered in blue and deselected item in white (without having written that code myself), I assume that my changes are overridden by JTree. So what would be the proper way to change the background color?
This is essentially my code:
JTree tree = new JTree();
tree.setCellRenderer(new MyCellRenderer());
///////
public class MyCellRenderer extends DefaultTreeCellRenderer{
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean isSelected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
JComponent c = (JComponent) super.getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, row, hasFocus);
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
MyData data = (MyData)node.getUserObject();
if(data.isX()){
c.setForeground(Color.blue);
c.setBackground(Color.gray);
}
return c;
}
}
Try adding a call to c.setOpaque(true)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With