2

我正在制作一个小型 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 个以上的面板。谢谢你

4

2 回答 2

2

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

于 2013-06-02T12:48:06.097 回答
0

所以首先你使用的是BorderLayout而不是GridBagLayout。实际上,使用 GridBagLayout 时,只要认为您的 Frame 是 Excel 页面,它就很容易使用。我也为初学者和专家写了一份关于如何正确使用 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();

}


}

这是你应该得到的: 使用 GridBagLayout 的 JPanel

于 2015-05-21T22:16:09.410 回答