3

以下のコードを使用しています。

 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、ツリーの出力は期待どおりになりません。

同じ問題を解決するには?

同じためにエディターを実装しませんでした。

4

2 に答える 2

3

のソース コードを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);
    }
于 2012-01-29T09:20:01.543 に答える
0

はい、基本的に少し変更してロビンが説明したように機能しました

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

足りる

于 2012-02-01T15:52:51.237 に答える