我想在一个 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();
}
}