我创建了一个JTree
。我需要更改特定节点的图标。能够setIcon
关闭和打开以及叶子节点,但我需要在JTree
中为指定节点设置图标。请详细说明一下。
答案 0 :(得分:3)
如果您知道如何更改默认图标,则会在TreeCellRenderer中发生这种情况。 您可以简单地实现自己的TreeCellRenderer,它具有比DefaultTreeCellRenderer更高级的图标确定。
这样的事情:
public class MyTreeCellRenderer implements TreeCellRenderer {
private final DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();
private final Icon specialIcon;
public MyTreeCellRenderer(Icon specialIcon) {
this.specialIcon = specialIcon;
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
defaultRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
if (needsSpecialIcon(tree, value, selected, expanded, leaf, row, hasFocus)) {
defaultRenderer.setIcon(specialIcon);
}
return defaultRenderer;
}
private boolean needsSpecialIcon(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
// check condition for special icon here
return false;
}
}
这基本上将默认行为委托给DefaultTreeCellRenderer,但如果您的特殊条件为真,则覆盖Icon。