2012-04-10 106 views
0

我試圖動態地將一些組件添加到JPanel,但不幸的是它們沒有出現。我只看到了在構造函數中添加的那些。動態添加組件到JPanel

更新版本(添加新JPanel,所有的組件會):

public class View extends JPanel { 

JPanel panel = new JPanel(); 
JLabel label; 
JLabel labels[]; 
JButton b1 = new JButton("OK"); 

public View() { 
    this.setLayout(new FlowLayout()); 
    this.add(panel); // adding a new JPanel 
    label = new JLabel("My label"); 
    panel.add(label); // adding label to the new panel (this one works) 
} 


public void showLabels() { 
    System.out.println("function showLabels called"); 

    labels = new JLabel[5]; 

    for (int i = 0; i < 5; i++) { 
     labels[i] = new JLabel("Label: " + i); 
     panel.add(labels[i]); // this one doesn't work 
    } 
    panel.add(b1); // this one doesn't work, too 
    this.validate(); // validating this class (parent container) 
    panel.validate(); // validating the panel, where all the components are 
    } 
} 

可惜的是沒有什麼改變。

+1

你嘗試調用'包()'父'JFrame'? – Jack 2012-04-10 17:21:21

+0

還沒有。僅僅調用revalidate()或其他的東西是不夠的? – user1170330 2012-04-10 17:22:26

+0

JPanel的佈局是什麼?一些組件可以在一些佈局中重疊,如BorderLayou。嘗試BoxLayout或FlowLayout。 – elias 2012-04-10 17:50:33

回答

4

在父容器上調用validate(),如Nested Layout Example所示。動態添加左下方的標籤。請注意,調用pack()可能會導致GUI的大小發生變化,而調用validate()則不會。如果您需要需要才能調整GUI的大小 - 請致電pack(),否則請致電validate()

+0

即使我將所有組件放在第一個JPanel上,然後將新JPanel放在第一個(父級)JPanel「View」並重新驗證並重新繪製兩者,但沒有任何更改... – user1170330 2012-04-10 18:18:28

+0

爲了更快地獲得更好的幫助, SSCCE](http://sscce.org/)竭盡全力。 – 2012-04-10 18:30:10

+0

*「重新驗證並重新繪製」* ..請注意,我提到了這兩種方法中的任何一種(理由很充分)。也許你正在考慮mre的答案(現在已經被刪除)。 – 2012-04-10 18:31:30