java GridBagLayout锚点 [英] java GridBagLayout anchor

查看:125
本文介绍了java GridBagLayout锚点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习GridBagLayout,这里的问题是,名称标签和combox没有显示在面板顶部,但是我将其锚定为NORTH.为什么?

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

推荐答案

您必须进行更改

gridBagConstraints.weighty = 0.0;

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.

更改weighty后的结果如下:

这篇关于java GridBagLayout锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆