我创建了一个JTree
. 我需要更改特定节点的图标。能够setIcon
关闭和打开以及叶子节点,但我需要在我的JTree
. 请对此有所了解。
问问题
1047 次
1 回答
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,但如果您的特殊条件为真,则会覆盖图标。
于 2012-12-09T17:35:21.067 回答