简体   繁体   English

java GridBagLayout锚点

[英]java GridBagLayout anchor

Learing GridBagLayout, The issue here is, the name label and combox don't show up on the top of the panel, but I have set its anchor to NORTH. 学习GridBagLayout,这里的问题是,名称标签和combox没有显示在面板的顶部,但我已将其锚点设置为NORTH。 Why ? 为什么?

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

You have to change 你必须改变

gridBagConstraints.weighty = 0.0;

to

gridBagConstraints.weighty = 1.0;

otherwise the area reserved for the component is slimmed to the size of the component, and it doesn't matter in which direction you "anchor" the component. 否则为组件保留的区域会缩小到组件的大小,并且无论您在哪个方向“锚定”组件。

The result after changing the weighty is the following: 改变weighty后的结果如下:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM