如何使我的Jtree看起来像下面的东西,加号和减号图标允许扩展和折叠?
目前,默认的JTree仅在双击时展开和折叠。我想覆盖这次双击以获得其他功能,让用户只需点击下面的减号和加号图标即可展开/折叠树。
答案 0 :(得分:10)
您必须更改L& F的Tree.collapsedIcon
和Tree.expandedIcon
属性并提供您自己的图标:
UIManager.put("Tree.collapsedIcon", new IconUIResource(new NodeIcon('+')));
UIManager.put("Tree.expandedIcon", new IconUIResource(new NodeIcon('-')));
这是我使用的图标,它是带有+/-内部的简单方形:
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;
}
}
答案 1 :(得分:4)
加号和减号图标,允许扩展和折叠?
这些是Windows LAF的默认图标。其他LAF有不同的图标。
您可以使用UIManager设置自己的图标。请参阅UIManager Defaults。
或者您只能为单个JTree使用自定义图标。请参阅Customizing a Tree's Display。
让用户只需点击下面的减号和加号图标即可展开/折叠树。
这是默认行为。
答案 2 :(得分:0)
或者只是想:)
class SourceListTreeUI extends BasicTreeUI
{
int offset = 10;
protected int getRowX(int row, int depth)
{
return totalChildIndent * (depth + offset);
}
}