一列布局不使用窗口的全宽

时间:2012-01-05 16:32:09

标签: java swing gridbaglayout

我想创建一个布局: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;

2 个答案:

答案 0 :(得分:5)

我认为你还需要:

gbc.weightx = 1.0;

请参阅How to Use a GrigBagLayout上关于权重x,权重约束的Swing教程中的部分。

答案 1 :(得分: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);
    }
}