【问题标题】:java GridBagLayout anchorjava GridBagLayout 锚点
【发布时间】:2011-06-17 22:10:32
【问题描述】:

学习 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();
    }
}

【问题讨论】:

    标签: java swing layout-manager gridbaglayout


    【解决方案1】:

    你必须改变

    gridBagConstraints.weighty = 0.0;
    

    gridBagConstraints.weighty = 1.0;
    

    否则为组件保留的区域会缩小到组件的大小,并且您“锚定”组件的哪个方向都没有关系。

    更改weighty后的结果如下:

    【讨论】:

    • 是的,你是对的。你的意思是,当anchor设置为NORTH时,weighty必须是1.0?
    • 好吧,如果你想给组件一些“区域”(大于组件本身)来放置,你需要一个非零权重。 (即,在这种特殊情况下,重量 0.1 也可以。)
    • 我总是混淆double值,1.0和0.5有什么区别?
    • 如果你在上面或下面有另一个组件,权重决定了哪个组件获得的空间最多。如果您有一个权重 1.0 和另一个权重 3.0,那么它们分别获得 25% 和 75% 的可用空间。
    • 在我的记忆中,weightx和weighty,最大值是1.0,对吗?
    猜你喜欢
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    相关资源
    最近更新 更多