1

我试图让带有两个面板的 GridBagLayout 分别占框架的 40% 和 60%,同时能够在其中包含组件,这很麻烦。

当我没有将按钮放在面板内时,它就像我想要的那样工作。

不太确定我做错了什么,我尝试将按钮的创建移动到创建 GridBagLayout 面板的位置,但它仍然不起作用。

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

public class Test{

public void display(){
    JFrame frame = new JFrame();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(900,650);
    frame.setVisible(true);

    JPanel test = new JPanel();
    test.setLayout(new GridBagLayout());
    GridBagConstraints c= new GridBagConstraints();

    JPanel left= new JPanel();
    JPanel right= new JPanel();

    c.fill = GridBagConstraints.VERTICAL - GridBagConstraints.HORIZONTAL;
    c.weightx = 0.4;
    c.gridx = 1;
    c.weighty = 1;
    test.add(left,c);
    c.weightx = .6;
    c.gridx = 2;
    test.add(right,c);

    JButton button= new JButton("A button");
    left.add(button,c);//If I do not add this, then it shows how I want it to be

    frame.add(test);
   }
}
4

2 回答 2

1

权重的作用在于它们描述了如何处理额外的空间。组件具有布局管理器在计算布局时使用的首选尺寸、最小尺寸和最大尺寸。然后 GridBagLayout 使用这些权重分割额外的空间。在您的情况下,我认为拆分的空间等于 900-button.getPreferredSize().width。您可能将 800 像素分成 320 和 480。

于 2012-01-15T18:32:59.220 回答
0

下面是一个使用 GridBagLayout 创建的面板示例:(不要担心摇摆工厂,只需创建一个组件即可)

private void buildSourcePanel() {

  JPanel pnlSource = new JPanel();

  GridBagLayout gbl_pnlSource = new GridBagLayout();
  gbl_pnlSource.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0};
  gbl_pnlSource.columnWidths = new int[]{0, 0, 100, 100, 25};
  pnlSource.setLayout(gbl_pnlSource);

  final JLabel lblFolderMask = swingFactory.createLabel(" SOURCE DIRECTORY ", null, null, SwingConstants.LEFT, SwingConstants.CENTER, true);
  pnlSource.add(lblFolderMask, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 5, 5, 0), 0, 0));

  txtSource = swingFactory.createTextField(null, "txtSource", null, SystemColor.textHighlight, SwingConstants.LEFT, false, true, "Source Directory");
  pnlSource.add(txtSource, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, 10, 1, new Insets(5, 0, 5, 5), 0, 0));

  final JButton btnBrowse = new JButton("Browse...");
  btnBrowse.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 0, false), new EmptyBorder(5, 5, 5, 5)));
  btnBrowse.setFont(new Font("Verdana", Font.BOLD, 14));
  pnlSource.add(btnBrowse, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 0, 5, 5), 0, 0));

  final JButton btnClear = new JButton("Clear...");
  btnClear.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 0, false), new EmptyBorder(5, 5, 5, 5)));
  btnClear.setFont(new Font("Verdana", Font.BOLD, 14));
  pnlSource.add(btnClear, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 0, 5, 5), 0, 0));

  lblStatus = swingFactory.createLabel(null, null, null, SwingConstants.CENTER, SwingConstants.CENTER, false);
  pnlSource.add(lblStatus, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 5, 5, 5), 0, 0));
}
于 2012-01-15T11:31:33.500 回答