我想在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();
}
}
答案 0 :(得分: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();
}
}