3

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());
}
spaceemotion
  • 1,404
  • 4
  • 24
  • 32
  • I faced this same issue and just add the code `this.selected = selected; this.hasFocus = hasFocus; ` it worked ,thanks . – Alter Hu Oct 17 '16 at 06:21

2 Answers2

3

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

tbodt
  • 16,609
  • 6
  • 58
  • 83
0

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.

Eel Lee
  • 3,513
  • 2
  • 31
  • 49
Hasan
  • 1