Java Jframe。无法显示多个组件

Java Jframe。无法显示多个组件,java,swing,layout,jframe,components,Java,Swing,Layout,Jframe,Components,我无法同时显示两个不同的组件 public class BandViewer { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(1000, 800); frame.setTitle("band"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

我无法同时显示两个不同的组件

public class BandViewer
{
   public static void main(String[] args)
   {
      JFrame frame = new JFrame();
      frame.setSize(1000, 800);
      frame.setTitle("band");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      BandComponent component = new BandComponent();
      ConcertBackground component1 = new ConcertBackground();
      frame.add(component);
      frame.add(component1);

      frame.setVisible(true);
   }
}

现在我在这个论坛上读到,你可以做一些事情来同时显示两者,但却无法弄清楚是如何做到的。有人能帮忙吗?我想要一个在另一个前面。他们有办法控制分层吗?提前谢谢

JFrame
中,布局管理器通常用于定位不同的组件

比如:

Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
JLayeredPane layeredPane = new JLayeredPane();

BandComponent component = new BandComponent();
ConcertBackground component1 = new ConcertBackground();
layeredPane.add(component, 0); // 0 to display underneath component1
layeredPane.add(component1, 1);

contentPane.add(layeredPane);
为您的
JFrame
设置基本布局管理器。还有一个
JLayeredPane
可用于指定z顺序-,例如:

Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
JLayeredPane layeredPane = new JLayeredPane();

BandComponent component = new BandComponent();
ConcertBackground component1 = new ConcertBackground();
layeredPane.add(component, 0); // 0 to display underneath component1
layeredPane.add(component1, 1);

contentPane.add(layeredPane);

以这种方式设置显示层次结构,对象中包含对象。我不确定什么是
BandComponent
ConcertBackground
类,但如果它们继承自Swing类,您可能必须设置首选大小或类似大小,以确保它们没有零大小

您遇到的问题是因为默认情况下,
JFrame
使用
BorderLayout
<代码>边框布局仅允许单个组件显示在其五个可用位置中的任意一个位置

要将多个组件添加到单个容器中,您需要配置布局或使用更能满足您需要的布局

更多示例,请参阅