2015-05-03 34 views
2

我想加载一个扩展JPanel的类,并且有另一个类的组件,这个组件也将JPanel扩展到另一个类中。 enter image description here加载包含另一个JPanel的JPanel

而这正是我需要实现: 例enter image description here

First.java

public class First extends JPanel{ 
     JPanel cont = new JPanel(); 
      public First(){ 
      cont.setBackground(Color.YELLOW); 
      } 
     } 

Second.java

public class Second extends JPanel{ 
     JPanel cont = new JPanel(); 
     First first_panel = new First(); 
      public Second(){ 
      cont.setBackground(Color.RED); 
      cont.add(first_panel); 
      } 
     } 

Container.java

public class Container extends JFrame{ 
     JFrame frame = new JFrame(); 
     JPanel cont = new JPanel(); 
     Second second_panel = new Second(); 
      public Container(){ 
      cont.setBackground(Color.GREEN); 
      cont.add(second_panel); 
      frame.add(cont); 
      frame.setVisible(true); 
      } 
     } 

我能够加载一个接一个班,但是当我试图加载包含另一个panel.class面板图形用户界面不显示它。逻辑有什么问题?有什么问题?

+0

为了更好地帮助越早,张贴[MCVE](http://stackoverflow.com/help/mcve)(最小完备可验证实施例)或[SSCCE](HTTP:// WWW .sscce.org /)(简短,独立,正确的例子)。 –

回答

3

显示的代码有两个基本问题。

  1. 每个类都扩展并有它处理的组件的一个实例。
  2. 这两个面板都没有任何内容会给它一个非零大小,也不会覆盖getPreferredSize方法,因此它们是0x0像素。

查看此MCVE的效果。

enter image description here

import java.awt.Color; 
import javax.swing.*; 

public class Container { 

    JFrame frame = new JFrame(); 
    JPanel cont = new JPanel(); 
    Second second_panel = new Second(); 

    public Container() { 
     cont.setBackground(Color.GREEN); 
     cont.add(second_panel.getPanel()); 
     frame.add(cont); 
     frame.pack(); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
    } 

    public static void main(String[] args) { 
     Runnable r = new Runnable() { 

      @Override 
      public void run() { 
       new Container(); 
      } 
     }; 
     SwingUtilities.invokeLater(r); 
    } 
} 

class Second { 

    JPanel cont = new JPanel(); 
    First first_panel = new First(); 

    public Second() { 
     cont.setBackground(Color.RED); 
     cont.add(new JLabel("Second")); 
     cont.add(first_panel.getPanel()); 
    } 

    public JComponent getPanel() { 
     return cont; 
    } 
} 

class First { 

    JPanel cont = new JPanel(); 

    public First() { 
     cont.setBackground(Color.YELLOW); 
     cont.add(new JLabel("First")); 
    } 

    public JComponent getPanel() { 
     return cont; 
    } 
}