[英]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.