8

我编写了一个自定义 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; 
    }
}
4

1 回答 1

12

尝试添加对c.setOpaque(true).

于 2013-05-11T18:35:50.730 回答