【问题标题】:Adding JPanels to JFrame with a for loop使用 for 循环将 JPanel 添加到 JFrame
【发布时间】:2013-10-17 22:38:59
【问题描述】:

我有一个 JPanel、窗口和一个 JPanel 和 JLabels 数组。我想向 JFrame 添加 5 个 JPanel,向每个 JPanel 添加一个 JLabel。每个 JPanel 将用于表示有关 Dice 的数据。

但是,当我运行代码时,只有最后一个 JPanel 出现在 JFrame 上,并带有文本“Dice 4”。我不明白为什么。

代码:

public static void main(String args[]) {

    JFrame window = new JFrame("DICE Frame");
    window.setVisible(true);
    window.setTitle("DIE");
    window.setSize(400, 200);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel[] diceView=new JPanel[5];
    JLabel[] labels=new JLabel[5];
    for(int i=0; i<diceView.length; i++) {

        diceView[i]=new JPanel();

        window.add(diceView[i]);

        labels[i]=new JLabel();
        labels[i].setText("Dice "+i);
        diceView[i].add(labels[i]);

    }
}

【问题讨论】:

  • 您使用的是什么布局管理器?显而易见的答案是您将所有面板放在同一位置,因此 4 在 3 之上,在 2 之上,即......

标签: java swing jframe jpanel jlabel


【解决方案1】:

JFrame 的 contentPane(调用 JFrame#add(...) 时添加的内容)默认使用 BorderLayout,每当您以默认方式向其中添加组件时,该组件都会添加 BorderLayout.CENTER。

解决方案是将您的其他 JPanel 添加到使用您认为需要的任何布局的 JPanel(或使用布局的嵌套 JPanel),然后将此容器 JPanel 添加到您的 JFrame、BorderLayout.CENTER。

请查看Layout Manager Tutorial 了解更多信息。要理解的一个关键概念是,您可以嵌套 JPanel,每个 JPanel 都使用自己的简单布局管理器,从而仅使用简单易用的布局管理器来实现复杂的布局。

【讨论】:

    【解决方案2】:

    因为您的 JPanel 一遍又一遍地添加,而 Dice 0、Dice 1、Dice 2、Dice 3 停留在 Dice 4 下方,因此您只能看到 Dice 4。如果您想查看其他 Dice,则应使用 flowlayout、boxlayout 等布局...

    【讨论】:

      【解决方案3】:

      您的JFrame 指定了默认的BorderLayout。尝试使用不同的布局,如下所示:

      window.setLayout(new FlowLayout());
      

      您将看到您的其他 JPanel。 Check this out for more detailed info

      【讨论】:

        猜你喜欢
        • 2013-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多