开发者

java swing - add color to my JTree node

I have a created a following renderer which renders the JTree with checkboxes and I want to add different color and icon to different nodes. How do I do it? Please help me. Thank you in advance.

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开发者_JS百科 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;
}    

}


The best place to learn about TreeCellRenderers is from the tutorial (at the bottom of the page).

Instead of adding renderer to BorderLayout.CENTER, you can just add a different icon of whatever color you like.


In order for your setBackground(Color.PINK) to have any visible effect, you should change the setOpaque(false) to setOpaque(true) in your constructor. That said, I second @John's suggestion that you read up on renderers in the Sun tutorials.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜