JTree nodes won't get visually selected

1.9k views Asked by At

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());
}
2

There are 2 answers

1
tbodt On BEST ANSWER

DefaultTreeCellRenderer extends JLabel, so try configuring this instead of label, then returning this.

0
Hasan On

After overriding the method as below :

getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) 

Create a JLabel instance with this code snippet:

JLabel label=(JLabel)super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);

And then override the method public Color getBackgroundSelectionColor() to your own color.