JTree节点不会在视觉上被选中 [英] JTree nodes won't get visually selected

查看:111
本文介绍了JTree节点不会在视觉上被选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以某种方式,我无法为我的JTree节点启用选择突出显示". 我正在项目中使用自定义单元格渲染器(很可能会导致此问题).

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

我在stackoverflow和其他站点上搜索了可能的解决方案,发现了"setOpaque"方法-完全没有变化.

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.

删除JLabel并添加这些行对我有用:

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扩展了JLabel,因此请尝试配置this而不是label,然后返回this.

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

这篇关于JTree节点不会在视觉上被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆