Somehow I am not able to enable a "select highlight" for my JTree nodes. I am working with a custom cell renderer in my project (which most likely causes this problem).
This is the full renderer class code:
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;
}
}
I searched on stackoverflow and other sites for possible solutions, found the "setOpaque" method - no change at all.
I am sure that it has to do something with the custom renderer, since the highlight is working perfectly fine in another project of mine.
Edit:
Removing the JLabel and adding those lines worked for me:
this.selected = selected;
this.hasFocus = hasFocus;
if (selected) {
super.setBackground(getBackgroundSelectionColor());
setForeground(getTextSelectionColor());
} else {
super.setBackground(getBackgroundNonSelectionColor());
setForeground(getTextNonSelectionColor());
}
DefaultTreeCellRenderer
extends JLabel, so try configuringthis
instead oflabel
, then returningthis
.