2011-01-09 66 views
8

我在尋找改變了我的JTree的不同的圖標(搖擺)改變JTree的節點圖標根據深度級別

Java文檔說明如何更改圖標,如果一個節點是葉與否,但是這真的不是我在尋找的東西。

對於我來說,如果一個節點是一片葉子,或者我只想更改圖標,如果節點處於三者的第一/第二/第三深度級別。

回答

8

作爲替代定製TreeCellRenderer,可以取代用於UI默認collapsedIconexpandedIcon

Icon expanded = new TreeIcon(true, Color.red); 
Icon collapsed = new TreeIcon(false, Color.blue); 
UIManager.put("Tree.collapsedIcon", collapsed); 
UIManager.put("Tree.expandedIcon", expanded); 

TreeIcon簡直是Icon接口的實現:

class TreeIcon implements Icon { 

    private static final int SIZE = 14; 
    private boolean expanded; 
    private Color color; 

    public TreeIcon(boolean expanded, Color color) { 
     this.expanded = expanded; 
     this.color = color; 
    } 

    //@Override 
    public void paintIcon(Component c, Graphics g, int x, int y) { 
     Graphics2D g2d = (Graphics2D) g; 
     g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
      RenderingHints.VALUE_ANTIALIAS_ON); 
     g2d.setPaint(color); 
     if (expanded) { 
      g2d.fillOval(x + SIZE/4, y, SIZE/2, SIZE); 
     } else { 
      g2d.fillOval(x, y + SIZE/4, SIZE, SIZE/2); 
     } 
    } 

    //@Override 
    public int getIconWidth() { 
     return SIZE; 
    } 

    //@Override 
    public int getIconHeight() { 
     return SIZE; 
    } 
} 
+1

嘿,感謝那個垃圾 - 幫助我度過了美好的時光。 – hamo 2011-04-11 04:37:54