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

試著忘記壹切 提交于 2019-12-22 00:19:04

问题


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.


回答1:


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.




回答2:


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



回答3:


Or simply think :)

class SourceListTreeUI extends BasicTreeUI
{

    int offset = 10;

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


来源:https://stackoverflow.com/questions/6590462/java-jtree-with-plus-minus-icons-for-expansion-and-collapse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!