2009-04-16 112 views
0

我試圖才達到基本上是在NetBeans特徵中的「在附上」在運行時:如何在運行時將組件與另一個容器放在一起?

比方說,我有這樣的組件層次:

Container 
    Label 1 
    Label 2 
    Label 3 

我要附上Label 2是這樣的:

Container 
    Label 1 
    Container 
     Label 2 
    Label 3 

而且我還想恢復它,即我想再次「拉起」標籤以獲得原始層次結構。

編輯:問題是,在運行時我只知道Label 2。任何其他組件(兄弟姐妹,父母,孩子)都是未知的。這消除了重建層次結構的可能性。

職高我相信我能找到一些方式通過遍歷組件層級得到這個功能,但我想知道:

有沒有更好的辦法?也許某種提供這種封裝功能的工具類?

編輯2:如何獲取佈局約束最初添加到容器的組件?我需要這些信息,因爲新容器必須使用相同的約束條件。此外,還原原始層次結構時,組件必須重新使用其舊約束。

回答

1

Container s也是Component s,因此可以將Container s包含在Container s中。

所以,也許是第一個國家將是沿(僞)線的東西:

Container container1 = new Container(); 
Label label1 = new Label(); 
Label label2 = new Label(); 
Label label3 = new Label(); 
container1.add(label1); 
container1.add(label2); 
container1.add(label3); 

過渡到第二狀態:

Container container2 = new Container(); 
container1.remove(label2); 
container2.add(label2); 
container2.add(container1); 

現在,label2移入container2該容器本身包含在container1中。

,並返回到原來的狀態:

container2.remove(label2); 
container1.add(label1); 
container1.remove(container2); 

編輯

如果我們只知道label2本身,也就是已經包含在一些Container,我們可以通過調用確定父ContainerComponentgetParent()方法。

將其應用於上面的代碼,更換線路製作container1有以下幾點:

Container container1 = label2.getParent(); 

如果你想獲得Component S的都在Container舉行的getComponents()方法可以被稱爲爲了檢索一個數組Component s。

+0

哦,對不起,我注意到我的問題很模糊。我會澄清...... – 2009-04-16 07:13:06

相關問題