简体   繁体   中英

TreeCellRenderer: how to set background color?

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; 
    }
}

尝试添加对c.setOpaque(true)的调用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM