2011-03-04 55 views
2

我的問題是這樣的如何添加差距到JTree

我想創建一個組件,並排顯示兩棵樹。這兩棵樹通常會非常相似,但可能會有一兩個不同。如果存在差異,即在一個分支中但不在另一個分支中,我希望沒有分支的樹爲它和每個失蹤的孩子顯示一個空的空間。

因此,它可能看起來像

 
left tree  right tree 
------------  ------------- 
+ Root   + Root 
|    | 
--Child A  --Child A 
|    | 
--Child B  | 
|    | 
--Child C  --Child C 

其相對簡單的刪除文本和圖標的,應該是使用自定義呈現空白的行。但是,這仍然留下了將兒童與父母垂直線相連的水平線。這是我的問題。

 
left tree  right tree 
------------  ------------- 
+ Root   + Root 
|    | 
--Child A  --Child A 
|    | 
--Child B  -- <--I want to remove this 
|    | 
--Child C  --Child C 

它也許bareable在這個簡單的例子,但在缺少分支有孩子太我最終有很多的空白連接線少。

我認爲一個潛在的替代方法是爲每棵樹創建一列JTreeTable,併爲缺失的分支清空單元格。雖然這意味着垂直線的一部分也會丟失。

任何幫助,想法或意見將非常appriciated。謝謝。

回答

3

考慮以下幾點:

class ReticentTreeUI extends BasicTreeUI { 

    private Set<Integer> hiddenRows = new HashSet<Integer>(); 

    public void hideRow(int row) { 
     hiddenRows.add(row); 
    } 

    @Override 
    protected void paintHorizontalPartOfLeg(Graphics g, 
     Rectangle clipBounds, Insets insets, Rectangle bounds, 
     TreePath path, int row, boolean isExpanded, 
     boolean hasBeenExpanded, boolean isLeaf) { 
     if (!hiddenRows.contains(row)) { 
      super.paintHorizontalPartOfLeg(g, clipBounds, insets, bounds, 
       path, row, isExpanded, hasBeenExpanded, isLeaf); 
     } 
    } 

    @Override 
    protected void paintRow(Graphics g, Rectangle clipBounds, 
     Insets insets, Rectangle bounds, TreePath path, int row, 
     boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { 
     if (!hiddenRows.contains(row)) { 
      super.paintRow(g, clipBounds, insets, bounds, path, row, 
       isExpanded, hasBeenExpanded, isLeaf); 
     } 
    } 

    @Override 
    protected void paintExpandControl(Graphics g, Rectangle clipBounds, 
     Insets insets, Rectangle bounds, TreePath path, int row, 
     boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { 
     if (!hiddenRows.contains(row)) { 
      super.paintExpandControl(g, clipBounds, insets, bounds, 
       path, row, isExpanded, hasBeenExpanded, isLeaf); 
     } 
    } 
} 

用例:

JTree tree = new JTree(); 
    ReticentTreeUI ui = new ReticentTreeUI(); 
    tree.setUI(ui); 
    ui.hideRow(2); 
+2

1重新格式化的代碼;如果不正確請回復。 – trashgod 2011-03-04 04:38:29

+0

謝謝n0weak,這個伎倆。 – Jamesy82 2011-03-05 01:49:33