的JPanel不内的另一个的JPanel

问题描述:

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

尝试改变

outerPanel.setLayout(null); 

outerPanel.setLayout(new FlowLayout()); 

或完全删除该setLayout的调用。

+0

就我所知,一个好主意,OP没有办法知道面板是否真的可见,因为它没有任何可见的东西,所以即使这个“有”解决了问题,他们也不会知道 – MadProgrammer

+1

(1+)但是,你可以摆脱setLayout(null)语句。 Swing设计用于布局管理器,JPanel的默认布局管理器是FlowLayout。 – camickr

+0

好点,编辑。 –