Java: JTree with plus/minus icons for expansion and collapse

javajtreeswing

How do I make my Jtree look like something below, with plus and minus icons that allows expansion and collapse?

Currently, the default JTree only expands and collapses when you double click. I want to override this double click for another functionality and let the user expand/collapse the tree by only clicking on the minus and plus icons such as below.

enter image description here

Best Answer

You have to change the Tree.collapsedIcon and Tree.expandedIcon properties of the L&F and supply your own icons:

UIManager.put("Tree.collapsedIcon", new IconUIResource(new NodeIcon('+')));
UIManager.put("Tree.expandedIcon",  new IconUIResource(new NodeIcon('-')));

Here is the icon I use, it's simple square with a +/- inside:

public class NodeIcon implements Icon {

    private static final int SIZE = 9;

    private char type;

    public NodeIcon(char type) {
        this.type = type;
    }

    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.setColor(UIManager.getColor("Tree.background"));
        g.fillRect(x, y, SIZE - 1, SIZE - 1);

        g.setColor(UIManager.getColor("Tree.hash").darker());
        g.drawRect(x, y, SIZE - 1, SIZE - 1);

        g.setColor(UIManager.getColor("Tree.foreground"));
        g.drawLine(x + 2, y + SIZE / 2, x + SIZE - 3, y + SIZE / 2);
        if (type == '+') {
            g.drawLine(x + SIZE / 2, y + 2, x + SIZE / 2, y + SIZE - 3);
        }
    }

    public int getIconWidth() {
        return SIZE;
    }

    public int getIconHeight() {
        return SIZE;
    }
}
Related Topic