JTree TreeCellRenderer在显示选择颜色时引发问题 [英] JTree TreeCellRenderer raising issue on showing the selection color

查看:267
本文介绍了JTree TreeCellRenderer在显示选择颜色时引发问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using this below piece of code:

 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中的任何组件时,都不会出现选择颜色. 我尝试使用:

Since I am passing/returning a label, so on selecting any component in the JTree, no selection color is coming. I tried to use:

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

但是,如果我返回comp,则树的输出将不会达到预期的水平.

But if I return comp, then the output of the tree is not coming as expected.

如何解决相同的问题?

我没有为此实现任何编辑器.

推荐答案

请查看

Please take a look at the source code of the DefaultTreeCellRenderer, which extends JLabel as well and is perfectly capable of setting a background color. I copy-pasted the relevant lines below:

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

这篇关于JTree TreeCellRenderer在显示选择颜色时引发问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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