【发布时间】:2011-09-29 05:56:04
【问题描述】:
如何使我的 Jtree 看起来像下面的东西,带有允许展开和折叠的加号和减号图标?
目前,默认的 JTree 只有在双击时才会展开和折叠。我想覆盖此双击以获得另一个功能,并让用户仅通过单击下面的减号和加号图标来展开/折叠树。
【问题讨论】:
如何使我的 Jtree 看起来像下面的东西,带有允许展开和折叠的加号和减号图标?
目前,默认的 JTree 只有在双击时才会展开和折叠。我想覆盖此双击以获得另一个功能,并让用户仅通过单击下面的减号和加号图标来展开/折叠树。
【问题讨论】:
您必须更改 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;
}
}
【讨论】:
带有允许展开和折叠的加号和减号图标?
这些是 Windows LAF 的默认图标。其他 LAF 有不同的图标。
您可以使用 UIManager 设置自己的图标。见UIManager Defaults。
或者您可以只为单个 JTree 使用自定义图标。见Customizing a Tree's Display。
让用户只需点击下面的减号和加号图标即可展开/折叠树。
这是默认行为。
【讨论】:
或者简单地认为:)
class SourceListTreeUI extends BasicTreeUI
{
int offset = 10;
protected int getRowX(int row, int depth)
{
return totalChildIndent * (depth + offset);
}
}
【讨论】: