Java GridBagLayout 锚点

6
学习GridBagLayout,问题在于名称标签和组合框没有显示在面板顶部,但我已将其锚定到NORTH。为什么?
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class Test2 {    
    public Test2() {
        JFrame frame = new JFrame();
        frame.setTitle("test");
        frame.getContentPane().setLayout(new GridLayout(1,2));
        frame.setSize(800, 600);

        JPanel panel1 = new JPanel();
        panel1.setLayout(new GridBagLayout());

        JLabel label = new JLabel("name");
        GridBagConstraints gridBagConstraints = new GridBagConstraints();   
        gridBagConstraints.anchor = GridBagConstraints.NORTH;
        gridBagConstraints.weightx = 0.0;
        gridBagConstraints.weighty = 0.0;
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        panel1.add(label, gridBagConstraints);

        String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
        JComboBox petList = new JComboBox(petStrings);
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.anchor = GridBagConstraints.NORTH;
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 0.0;
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        panel1.add(petList, gridBagConstraints);    

        frame.getContentPane().add(panel1);
        frame.getContentPane().add(new JPanel());       

        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);      
    }

    public static void main(String[] args) {
        new Test2();
    }
}
1个回答

18

你需要进行改变

gridBagConstraints.weighty = 0.0;

gridBagConstraints.weighty = 1.0;
否则,为组件预留的区域将缩小到组件的大小,无论您以哪个方向“锚定”该组件都没有关系。
更改weighty后的结果如下所示: enter image description here

是的,你说得对。你的意思是,当锚点设置为NORTH时,weighty必须为1.0吗? - user595234
如果您希望组件被放置在一些“区域”(大于组件本身)中,则需要非零权重。(即,在这种特定情况下,权重0.1也可以使用。) - aioobe
我总是混淆双精度浮点值,1.0和0.5之间有什么区别? - user595234
如果您有另一个组件在上方或下方,则权重确定哪个组件获得最多的空间。如果您有一个权重为1.0,另一个权重为3.0,则它们分别获得可用空间的25%和75%。 - aioobe
在我的记忆中,weightx和weighty的最大值是1.0,这正确吗? - user595234
不,我不相信它们有上限。 - aioobe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接