TreeCellRenderer:如何设置背景颜色?

时间:2013-05-11 18:28:53

标签: java swing jtree

我编写了一个自定义TreeCellRenderer来更改组件外观。一切正常,但setBackground没有效果。代码肯定会执行,因为前景色始终会正确更改。由于所选项目以蓝色呈现并且取消选择白色项目(没有自己编写该代码),我认为我的更改被JTree覆盖。那么改变背景颜色的正确方法是什么?

这基本上是我的代码:

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

1 个答案:

答案 0 :(得分:9)

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