0

我想在一个 GridBagLayout 中设置两个元素,它们都应该在布局的顶部(第二个元素应该从第一个元素的底部开始)。

此外,第二个元素应将空间填充到底部。

第一个元素的gbc.anchor = GridBagConstraint.NORTH作品,但第二个元素不会粘在可用空间的顶部。相反,它会停留在布局后半部分的顶部。

截屏

那是我的代码:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class TestFrame extends JFrame{

    public TestFrame(){
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        this.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        gbc.anchor = GridBagConstraints.NORTH;
        gbc.weighty = 1.0;

        JPanel one = new JPanel();
        one.setPreferredSize(new Dimension(200,200));
        one.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        JPanel two = new JPanel();
        two.setPreferredSize(new Dimension(200,200));
        two.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        this.add(one, gbc);

        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.VERTICAL;

        this.add(two, gbc);

        this.pack();
        this.setVisible(true);
    }

    public static void main(String[] args){
        new TestFrame();
    }
}
4

1 回答 1

0

我刚刚找到了一个解决方案:如果我将wheighty第一个元素设置为0.0并且仅将weighty第二个元素设置为1.0它按计划工作。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class TestFrame extends JFrame{

    public TestFrame(){
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        this.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        gbc.anchor = GridBagConstraints.NORTH;
        gbc.weighty = 0.0;

        JPanel one = new JPanel();
        one.setPreferredSize(new Dimension(200,200));
        one.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        JPanel two = new JPanel();
        two.setPreferredSize(new Dimension(200,200));
        two.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        this.add(one, gbc);

        gbc.gridy = 1;
        gbc.weighty = 0.0;
        gbc.fill = GridBagConstraints.VERTICAL;

        this.add(two, gbc);

        this.pack();
        this.setVisible(true);
    }

    public static void main(String[] args){
        new TestFrame();
    }
}
于 2013-04-11T13:32:02.073 回答