3
我已經編寫了一個自定義TreeCellRenderer以更改組件外觀。一切正常,但setBackground
沒有任何效果。代碼是肯定執行的,因爲前景色總是正確地改變。由於選定的項目以藍色呈現,而取消選定的項目以白色呈現(沒有自己編寫代碼),因此我認爲我的更改被JTree覆蓋。那麼改變背景顏色的正確方法是什麼?TreeCellRenderer:如何設置背景顏色?
這基本上是我的代碼:
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;
}
}