本文介绍了TreeCellRenderer:如何设置背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经编写了一个自定义TreeCellRenderer来更改组件的外观.一切正常,除了setBackground
不起作用.该代码肯定会执行,因为前景色始终正确更改.由于选定的项目以蓝色呈现,而取消选择的项目以白色呈现(我自己没有编写该代码),因此我假设我的更改被JTree覆盖.那么改变背景颜色的正确方法是什么?
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?
这本质上是我的代码:
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)
的呼叫.
这篇关于TreeCellRenderer:如何设置背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!