2017-02-14 105 views
0
class ABC extends JFrame { 
    public JPanel createGUI() 
    { 
     JPanel outerPanel = new JPanel(); 
     outerPanel.setLayout(null); 

     JLabel top = new JLabel(); 
     top.setBounds(40,40,400,30); 
     top.setText("Hello World"); 
     outerPanel.add(top); 

     int l = getLength(); 
     JPanel innerPanel = new JPanel(); 
     if(l==0) 
     { 
      innerPanel.setLayout(null); 
      JLabel empty = new JLabel("No Data Found"); 
      empty.setBounds(80,150,300,30); 
      innerPanel.add(empty); 
     } 
     else 
     { 
      innerPanel.setLayout(new GridLayout(l,4,5,5)); 
      for(int i=0;i<l;i++) 
      { 
       innerPanel.add(new JLabel("Text1"); 
       innerPanel.add(new JLabel("Text2"); 

       JButton b1 = new JButton("Button1"); 
       innerPanel.add(b1); 
       JButton b2 = new JButton("Button2"); 
       innerPanel.add(b2); 
      }   
     } 
     outerPanel.add(innerPanel); 
     return outerPanel; 
    } 
} 

在上面的代碼中顯示的innerPanel不顯示也不任何錯誤occurs.Any知道如何顯示的innerPanel作爲使用 的getContentPane內部的outerPanel.I嘗試( ).add(innerPanel) 但它沒有工作。的JPanel不內的另一個的JPanel

+0

我認爲問題是innerPanel將具有getPreferredSize()== 0,0 ...因爲它沒有任何內容,所以它不會被FlowLayout(JPanel的默認佈局管理器)展開if它被直接添加到contentPane中,因此可能會顯示outerPanel,因爲在默認contentPane上調用add(component)會將其添加到BorderLayout.CENTER – ControlAltDel

+0

您甚至知道顯示內容和不顯示內容。您沒有添加佔用空間的視覺元素。您的標籤是空的,沒有設置邊界,因此所有元素的大小都將爲零。 – markbernard

+0

@markbernard在這裏,我添加了剛纔添加的最小代碼,我認爲這將提供一個解決方案。我確實在outerPanel中設置了可視元素以及innerPanel,其中outerPanel可以正確渲染。 – srk20

回答

1

嘗試改變

outerPanel.setLayout(null); 

outerPanel.setLayout(new FlowLayout()); 

或完全刪除該setLayout的調用。

+0

就我所知,一個好主意,OP沒有辦法知道面板是否真的可見,因爲它沒有任何可見的東西,所以即使這個「有」解決了問題,他們也不會知道 – MadProgrammer

+1

(1+)但是,你可以擺脫setLayout(null)語句。 Swing設計用於佈局管理器,JPanel的默認佈局管理器是FlowLayout。 – camickr

+0

好點,編輯。 –

相關問題