Java:JTree带有正/负图标,用于扩展和折叠?

KJW*_*KJW 1 java swing jtree

如何使我的Jtree看起来像下面的东西,加号和减号图标允许扩展和崩溃?

目前,默认的JTree仅在双击时才会展开和折叠.我想覆盖这个双击以获得另一个功能,让用户只需点击下面的减号和加号图标即可展开/折叠树.

在此输入图像描述

Emm*_*urg 10

你必须改变Tree.collapsedIconTree.expandedIcon的L&F的特性,并提供自己的图标:

UIManager.put("Tree.collapsedIcon", new IconUIResource(new NodeIcon('+')));
UIManager.put("Tree.expandedIcon",  new IconUIResource(new NodeIcon('-')));
Run Code Online (Sandbox Code Playgroud)

这是我使用的图标,它是带有+/-内部的简单方形:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)