【问题标题】:JTree TreeCellRenderer raising issue on showing the selection colorJTree TreeCellRenderer 在显示选择颜色时引发问题
【发布时间】:2012-02-21 12:21:09
【问题描述】:

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

 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,那么树的输出不会像预期的那样出现。

如何解决?

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

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE
  • +1 for not 扩展组件 :-) 渲染器的工作是根据传递的参数配置渲染组件的视觉属性(如字体和颜色) - 进入 getXXRenderingComponent

标签: java swing jtree cellrenderer


【解决方案1】:

请看一下source code of the DefaultTreeCellRenderer,它也扩展了JLabel,并且完全能够设置背景颜色。我复制粘贴了以下相关行:

  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 a) extending 一个组件是肮脏的设计 b) 混合对 super 的调用,这很痛苦(在默认的表格单元格渲染器中臭名昭著的颜色记忆)
  • @kleopatra 我应该让我的答案更清楚。我想说明使用JLabel 完全有可能获得所需的行为,并以DefaultTreeCellRenderer 为例,因为它节省了我编写一些代码的工作量。现在我再次阅读了我的答案,我发现它可能会被误解
【解决方案2】:

是的,它基本上按照 Robin 解释的方式工作

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

够了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多