【发布时间】:2013-04-11 13:24:20
【问题描述】:
我想将 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();
}
}
【问题讨论】:
标签: java swing gridbaglayout