[英]Java: JTree with plus/minus icons for expansion and collapse?
如何使我的 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 默认值。
或者,您可以仅对单个 JTree 使用自定义图标。 请参阅自定义树的显示。
让用户仅通过单击减号和加号图标来展开/折叠树,如下所示。
这是默认行为。
或者简单地认为:)
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.