JTree nodes won't get visually selected

馋奶兔 提交于 2019-12-23 19:24:21

问题


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

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/17755723/jtree-nodes-wont-get-visually-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!