2

我想创建一个布局:2 行,1 列。第一行应占窗口高度的 70%,第二行应占窗口高度的 30%。我通过weighty使用GridBagConstraints.

但是我的组件的宽度有问题,因为当我调整应用程序窗口的大小时,组件保持在中心,它的宽度是恒定的,并且我在组件的左侧和右侧得到一个空白(即使我设置fillBOTH)。当我更改窗口的高度(组件调整大小并填充窗口的整个高度)时,不会出现此问题。

在我的限制之下:

firstConstraints.gridx = 0;
firstConstraints.gridy = 0;  
firstConstraints.weighty = 0.7;
firstConstraints.fill = GridBagConstraints.BOTH;

secondConstraints.gridx = 0;
secondConstraints.gridy = 1;  
secondConstraints.weighty = 0.3;
secondConstraints.fill = GridBagConstraints.BOTH;
4

2 回答 2

5

I think you also need:

gbc.weightx = 1.0;

See the secton from the Swing tutorial on How to Use a GrigBagLayout that talks about the weightx, weighty constraints.

于 2012-01-05T16:48:32.533 回答
1

简单的例子

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

public class BorderPanels extends JFrame {

    private static final long serialVersionUID = 1L;

    public BorderPanels() {
        getContentPane().setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        JPanel panel1 = new JPanel();
        Border eBorder = BorderFactory.createEtchedBorder();
        panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "70pct"));
        gbc.gridx = gbc.gridy = 0;
        gbc.gridwidth = gbc.gridheight = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        gbc.weightx = gbc.weighty = 70;
        getContentPane().add(panel1, gbc);
        JPanel panel2 = new JPanel();
        panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "30pct"));
        gbc.gridy = 1;
        gbc.weightx = 30;
        gbc.weighty = 30;
        gbc.insets = new Insets(2, 2, 2, 2);
        getContentPane().add(panel2, gbc);
        pack();
    }

    public static void main(String[] args) {
        new BorderPanels().setVisible(true);
    }
}
于 2012-01-05T17:23:49.890 回答