【问题标题】:java swing - add color to my JTree nodejava swing - 为我的 JTree 节点添加颜色
【发布时间】:2011-01-19 23:25:01
【问题描述】:

我创建了一个以下渲染器,它使用复选框渲染 JTree,我想为不同的节点添加不同的颜色和图标。我该怎么做?请帮我。提前谢谢你。

class CheckTreeCellRenderer extends JPanel implements TreeCellRenderer {
private CheckTreeSelectionModel selectionModel;
private TreeCellRenderer delegate;
private TristateCheckBox checkBox = new TristateCheckBox("",null,true);
public static final State NOT_SELECTED = new State();
public static final State SELECTED = new State();
public static final State DONT_CARE = new State();

public CheckTreeCellRenderer(TreeCellRenderer delegate, CheckTreeSelectionModel selectionModel) {
    this.delegate =  delegate;
    this.selectionModel = selectionModel;
    setLayout(new BorderLayout());
    setOpaque(false);
    checkBox.setState(Boolean.TRUE);
    revalidate();
    checkBox.setOpaque(false);
}

public Component getTreeCellRendererComponent
        (JTree tree, Object value, boolean selected, boolean expanded,
        boolean leaf, int row, boolean hasFocus) {

    Component renderer = delegate.getTreeCellRendererComponent
            (tree, value, selected, expanded, leaf, row, hasFocus);

    TreePath path = tree.getPathForRow(row);

    if(path!=null){
        if(selectionModel.isPathSelected(path, true)) {
            checkBox.setState(Boolean.TRUE);
        }
        else {
            checkBox.setState
                    (selectionModel.isPartiallySelected(path) ? null : Boolean.FALSE);
        }
    }
    setBackground(Color.pink);

    removeAll();
    add(checkBox, BorderLayout.WEST);
    add(renderer, BorderLayout.CENTER);
    return this;
}    

}

【问题讨论】:

  • 我已经多次回答同一个问题,我想我会通过这个。
  • 那为什么还要评论呢?相反,投票关闭并引用重复的答案。至少这样 OP 可以引用重复的问题。
  • 您好,朋友,对不起。我想我问了一个重复的问题。其实我不知道在哪里寻找同样的问题。如果已经回答,请告诉我在哪里可以得到它。我请求你帮助我。

标签: java swing jtree


【解决方案1】:

了解 TreeCellRenderers 的最佳地点是tutorial(位于页面底部)。

除了将renderer 添加到BorderLayout.CENTER 之外,您还可以添加一个您喜欢的任何颜色的不同图标。

【讨论】:

    【解决方案2】:

    为了让您的setBackground(Color.PINK) 产生任何可见的效果,您应该在构造函数中将setOpaque(false) 更改为setOpaque(true)。也就是说,我赞同@John 的建议,即您阅读 Sun 教程中的渲染器。

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 2011-12-17
      相关资源
      最近更新 更多