不知何故,我无法为我的 JTree 节点启用“选择突出显示”。 我在我的项目中使用自定义单元格渲染器(这很可能会导致此问题)。
这是完整的渲染器类代码:
protected class ProfessionTreeCellRenderer extends DefaultTreeCellRenderer {
private final JLabel label;
public ProfessionTreeCellRenderer() {
label = new JLabel();
setBackgroundSelectionColor(Color.BLUE);
setOpaque(true);
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Object o = ((DefaultMutableTreeNode) value).getUserObject();
if (o instanceof Profession) {
Profession profession = (Profession) o;
label.setIcon(profession.getIcon());
label.setText(profession.getDisplayName());
} else if(o instanceof NPC) {
label.setIcon(QuestEdit.getIcon("npc"));
label.setText(((NPC) o).getName());
} else {
label.setIcon(null);
label.setText("" + value);
}
return label;
}
}
我在 stackoverflow 和其他网站上搜索了可能的解决方案,找到了“setOpaque”方法 - 完全没有变化。
我确信它必须对自定义渲染器做一些事情,因为高光在我的另一个项目中工作得很好。
编辑:
删除 JLabel 并添加这些行对我有用:
this.selected = selected;
this.hasFocus = hasFocus;
if (selected) {
super.setBackground(getBackgroundSelectionColor());
setForeground(getTextSelectionColor());
} else {
super.setBackground(getBackgroundNonSelectionColor());
setForeground(getTextNonSelectionColor());
}
最佳答案
DefaultTreeCellRenderer
扩展了 JLabel,因此请尝试配置 this
而不是 label
,然后返回 this
。
关于java - JTree 节点不会在视觉上被选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17755723/