问题
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