简体   繁体   中英

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

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.

在此处输入图像描述

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

with plus and minus icons that allows expansion and collapse?

These are the default icons for the Windows LAF. Other LAF's have different icons.

You can set your own icons by using the UIManager. See UIManager Defaults .

Or you can use custom icons for a single JTree only. See Customizing a Tree's Display .

let the user expand/collapse the tree by only clicking on the minus and plus icons such as below.

This is the default behaviour.

Or simply think:)

class SourceListTreeUI extends BasicTreeUI
{

    int offset = 10;

    protected int getRowX(int row, int depth)
    {
        return totalChildIndent * (depth + offset);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM