tags:

views:

399

answers:

2

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

}

+1  A: 

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.

John
+1  A: 

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.

akf