【问题标题】:How to Insert multiple panels in GridBagLayout如何在 GridBagLayout 中插入多个面板
【发布时间】:2013-06-02 12:45:11
【问题描述】:

我正在制作一个小型 GUI,它需要在 JFrame 中添加至少 4 个面板。我正在使用 GridBagLayout。这些面板中的每一个都有一些不同长度的标签和文本区域。 我插入了 3 帧:

    jf.add(panel1, BorderLayout.NORTH);
    jf.add(panel2, BorderLayout.CENTER);
    jf.add(panel4, BorderLayout.SOUTH);

这里的 jf 是框架。现在我多了一个面板(Panel3),它必须在面板 2 和面板 4 之间。请给我一些想法,我们如何插入超过 3 个面板。 谢谢你

【问题讨论】:

  • 您可能应该看看this guide,以帮助您选择适合您需要的布局。据我了解,您希望垂直显示面板。为此,BoxLayout 可能会有所帮助。

标签: java swing jframe jpanel gridbaglayout


【解决方案1】:

将框架内容窗格的布局更改为 BorderLayout 以外的布局,然后将面板添加到您想要的位置。您可能应该使用 1 列和 4 行的 GridLayout。由于您掌握了所有面板的 GridBagLayout,因此如果您愿意,也可以将 GridBagLayout 用于内容窗格。

【讨论】:

  • 要么是那个,要么是页面轴上的 BoxLayout。
【解决方案2】:

首先,您使用的是 BorderLayout 而不是 GridBagLayout。实际上,使用 GridBagLayout 时,只要认为您的 Frame 是 Excel 页面,它就很容易使用。我也为初学者和专家写了一个full and very useful guide,关于如何正确使用GridBagLayout。

代码如下:

package prueba;

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

public class BlocPrueb extends JFrame{

JPanel container;   
JPanel panel1;
JPanel panel2;
JPanel panel3;
JPanel panel4;

GridBagLayout cockatoo;
GridBagConstraints c;

  public BlocPrueb(){

      JButton g = new JButton("JPanel1");
      JButton h = new JButton("JPanel2");
      JButton j = new JButton("JPanel3");
      JButton k = new JButton("JPanel4");

      cockatoo = new GridBagLayout();
      c = new GridBagConstraints();

      container = new JPanel();
      container.setLayout(cockatoo);

      panel1 = new JPanel();
      panel2 = new JPanel();
      panel3 = new JPanel();
      panel4 = new JPanel();


      //Will use BorderLayout in the panels, cause its a demostration but it works as well as if it was the only panel in the JFrame.
      panel1.setLayout(new BorderLayout());
      panel1.add(g);

      panel2.setLayout(new BorderLayout());
      panel2.add(h);

      panel3.setLayout(new BorderLayout());
      panel3.add(j);

      panel4.setLayout(new BorderLayout());
      panel4.add(k);

      c.gridx = 0;
      c.gridy = 0;
      c.fill = GridBagConstraints.BOTH;
      container.add(panel1, c);

      c.gridx = 1;
      c.gridy = 0;
      container.add(panel2, c);

      c.gridx = 2;
      c.gridy = 0;
      container.add(panel3, c);

      c.gridx = 3;
      c.gridy = 0;
      container.add(panel4, c);

      getContentPane().add(container);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setTitle("Cockatoo Panels inside a JFrame (GridBagLayout)");
      pack();
      setResizable(true);
      setLocationRelativeTo(null);
      setVisible(true);

  } 

    public static void main (String args[]){

        BlocPrueb v = new BlocPrueb();

}


}

这是您应该得到的:

【讨论】:

  • @Antorio,完整且非常有用的指南的链接在哪里?您在答案中提供的那个已损坏。
猜你喜欢
  • 2013-01-23
  • 2020-03-24
  • 2016-08-21
  • 1970-01-01
  • 2012-05-20
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 2022-12-19
相关资源
最近更新 更多