JTree TreeCellRenderer提出了显示选择颜色的问题

时间:2012-01-29 06:43:52

标签: java swing jtree cellrenderer

我正在使用下面这段代码:

 class CountryTreeCellRenderer implements TreeCellRenderer {
        private JLabel label;

        CountryTreeCellRenderer() {
            label = new JLabel();
        }

        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 Country) {
                Country country = (Country) o;
                label.setIcon(new ImageIcon(country.getFlagIcon()));
                label.setText(country.getName());
            } else {
                label.setIcon(null);
                label.setText("" + value);
            }
            return label;
        }
    }

由于我传递/返回标签,所以选择JTree中的任何组件时,都不会有选择颜色。 我试着用:

JComponent comp = (JComponent) super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
comp.setOpaque(true);
if(selected)
comp.setBackground(Color.RED);

但是如果我返回comp,则树的输出不会按预期进行。

如何解决这个问题?

我没有实现任何编辑器。

2 个答案:

答案 0 :(得分:3)

请查看source code of the DefaultTreeCellRendererJLabel也扩展 if (selected) { super.setBackground(getBackgroundSelectionColor()); setForeground(getTextSelectionColor()); if (hasFocus) setBorderSelectionColor(UIManager.getLookAndFeelDefaults(). getColor("Tree.selectionBorderColor")); else setBorderSelectionColor(null); } else { super.setBackground(getBackgroundNonSelectionColor()); setForeground(getTextNonSelectionColor()); setBorderSelectionColor(null); } ,完全能够设置背景颜色。我复制粘贴下面的相关行:

{{1}}

答案 1 :(得分:0)

是的,它的工作正如Robin所解释的那样基本上改变了

if(selected){
            label.setBackground(Color.YELLOW);
            label.setForeground(Color.GREEN);
        }else
             {
            label.setBackground(Color.WHITE);
            label.setForeground(Color.BLACK);
             //setBorderSelectionColor(null);
             }

足够

相关问题