【问题标题】:Jframe. Cant get multiple components to display框架。无法显示多个组件
【发布时间】:2013-11-13 00:38:10
【问题描述】:

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

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);
   }
}

现在我在这个论坛上读到,您可以做一些事情来同时显示两者,但无法弄清楚它是如何完成的。有人可以帮忙吗?我想让一个在另一个前面。他们有什么方法可以控制分层吗?提前致谢。

【问题讨论】:

    标签: java swing layout jframe components


    【解决方案1】:

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

    类似:

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

    为您的JFrame 设置一个基本布局管理器。还有一个 JLayeredPane 允许您指定 z 顺序 - docs page,例如:

    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);
    

    以这种方式设置显示层次结构,对象包含对象。我不确定 BandComponentConcertBackground 类是什么,但如果它们继承自 Swing 类,您可能需要设置首选大小或类似大小,以确保它们的大小不为零!

    【讨论】:

      【解决方案2】:

      您遇到的问题是因为JFrame 默认使用BorderLayoutBorderLayout 只允许单个组件出现在它的五个可用位置中的任何一个。

      要将多个组件添加到单个容器中,您需要配置布局或使用更符合您需求的布局...

      查看A Visual Guide to Layout Managers 了解更多示例

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-13
        • 2011-03-11
        • 2021-02-25
        • 2017-07-11
        • 1970-01-01
        相关资源
        最近更新 更多