2016-11-28 120 views
1

所以我创建了三个类,主要方法类,Frame类和JPanel类。在JPanel类中,我想添加三个JPanel,一个在JFrame的顶部,一个在中心,一个在底部。我对班JPanel并JFrame的代码如下: 的JPanel:将JPanels添加到主面板

public class ConcertPanel extends JPanel 
{ 
public ConcertPanel() 
{ 
    JPanel ConcertPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); 

    JPanel Panel1 = new JPanel(); 
    Panel1.setSize(800,200); 
    Panel1.setBackground(Color.BLUE); 

    JPanel Panel2 = new JPanel(); 
    Panel2.setSize(800,400); 
    Panel1.setBackground(Color.GREEN); 

    JPanel Panel3 = new JPanel(); 
    Panel3.setSize(800,200); 
    Panel1.setBackground(Color.GRAY); 

    this.add(Panel1); 
    this.add(Panel2); 
    this.add(Panel3); 
}   
} 

public class ConcertFrame extends JFrame 
{ 
private ConcertPanel controlPane; 
// The constructor 
public ConcertFrame() 
{ 
    controlPane = new ConcertPanel() ; 
    this.add(controlPane); 
.... 

当这个项目跑,没有错误显示出来,但是当JFrame中弹出它不给我三个不同它内部只有一个小灰色的盒子,但顶部只有一个小灰盒子。任何人都可以告诉我为什么或帮助?

+0

请参阅编辑回答。请让我知道是否有什么东西还不清楚。\ –

回答

1

一个主要问题是代码没有考虑到preferredSize和布局管理器。

所有颜色JPanels的首选尺寸是0,0,并且设置尺寸的尺寸不会影响这一点。由于它们被添加到默认布局管理器FlowLayout的JPanel中,因此布局不会增加其大小。因此,由于大多数布局管理器都遵循首选大小而不是实际大小,并且FlowLayout不会更改此设置,所以JPanels 已添加,但从未见过。

如果所有组件都具有相同的大小,请考虑对主容器使用其他布局,例如GridLayout,或者如果所有组件都放在一行或一列中,则使用BoxLayout。考虑重写getPreferredSize方法,但要小心且只在需要时。

一个“作弊”解决方案是将setSize(...)更改为setPreferredSize(new Dimensnion(...)),但这是不满意的。

例如:

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

@SuppressWarnings("serial") 
public class ColorPanels extends JPanel { 
    public ColorPanels() { 
     setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); 
     add(new ColorPanel(Color.BLUE, 800, 200)); 
     add(new ColorPanel(Color.GREEN, 800, 400)); 
     add(new ColorPanel(Color.GRAY, 800, 200)); 
    } 

    private static class ColorPanel extends JPanel { 

     private int w; 
     private int h; 

     public ColorPanel(Color color, int w, int h) { 
      this.w = w; 
      this.h = h; 
      setBackground(color); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      if (isPreferredSizeSet()) { 
       return super.getPreferredSize(); 
      } 
      return new Dimension(w, h); 
     } 

    } 

    private static void createAndShowGui() { 
     ColorPanels mainPanel = new ColorPanels(); 

     JFrame frame = new JFrame("ColorPanels"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(() -> createAndShowGui()); 
    } 
} 
+0

对不起,我需要一段时间才能回来,但我想用这个帮助,并尝试让它与我自己的问题有关,它最终已经!感谢您的帮助!! – May

+0

@五月:不客气。另外,请看看[某人的答案](http://stackoverflow.com/help/someone-answers)。 –