简体   繁体   English

Java:带有用于展开和折叠的加号/减号图标的 JTree?

[英]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?如何使我的 Jtree 看起来像下面的东西,带有允许展开和折叠的加号和减号图标?

Currently, the default JTree only expands and collapses when you double click.目前,默认的 JTree 只有在双击时才会展开和折叠。 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:您必须更改 L&F 的Tree.collapsedIconTree.expandedIcon属性并提供您自己的图标:

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.这些是 Windows LAF 的默认图标。 Other LAF's have different icons.其他 LAF 有不同的图标。

You can set your own icons by using the UIManager.您可以使用 UIManager 设置自己的图标。 See UIManager Defaults .请参阅UIManager 默认值

Or you can use custom icons for a single JTree only.或者,您可以仅对单个 JTree 使用自定义图标。 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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