2015-05-03 82 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; 
    } 
} 
相關問題