JTree TreeCellRenderer raising issue on showing the selection color

不问归期 提交于 2020-01-14 16:49:09

问题


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

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

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

How to resolve the same?

I did not implement any Editor for the same.


回答1:


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



回答2:


Yes it worked as explained by Robin by bit of change basically

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

enough



来源:https://stackoverflow.com/questions/9051463/jtree-treecellrenderer-raising-issue-on-showing-the-selection-color

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