简体   繁体   English

gridbaglayout中的权重不正确

[英]Incorrect weighty in gridbaglayout

I want to make a GUI in Java, using GridBagLayout. 我想使用GridBagLayout在Java中创建GUI。 This is what I want in the end : 这是我最终想要的:

在此处输入图片说明

Therefore, I followed some instructions I found on the Internet, and here is the code I wrote : 因此,我遵循了在Internet上找到的一些说明,这是我编写的代码:

    Panel panel = new Panel();
    panel.setLayout(new GridBagLayout());
    GridBagConstraints gc = new GridBagConstraints();
    gc.fill = GridBagConstraints.BOTH;
    gc.insets = new Insets(5, 5, 5, 5);
    gc.weightx = 7;
    gc.weighty = 7;
    panel.add(new JLabel("title"), gc, 0, 0, 2, 1);
    panel.add(new JButton("button 1"), gc, 2, 0, 1, 1);
    panel.add(new JButton("button 2"), gc, 3, 0, 1, 1);
    panel.add(new JButton("button 3"), gc, 4, 0, 1, 1);
    panel.add(new JButton("button 4"), gc, 5, 0, 1, 1);
    panel.add(new JButton("button 5"), gc, 6, 0, 1, 1);
    panel.add(new JLabel("subtitle"), gc, 0, 1, 7, 1);   
    panel.add(new JButton("list"), gc, 0, 2, 2, 4);  
    panel.add(new JButton("button"), gc, 0, 6, 1, 1);    
    panel.add(new JButton("button"), gc, 1, 6, 1, 1);
    panel.add(new JButton("table"), gc, 2, 2, 5, 5);

My function add : 我的功能添加:

public void add(Component component, GridBagConstraints constraints, int x, int y, int width, int height) {
    constraints.gridx = x;
    constraints.gridy = y;
    constraints.gridwidth = width;
    constraints.gridheight = height;
    this.add(component, constraints);
}

But, I have this in the end : 但是,我最后有这个:

在此处输入图片说明

As you can see, the table does not take 5 cells in height at all, and the list does not take 4 cells. 如您所见,表格根本不占用5个单元格的高度,列表也不占用4个单元格的高度。 Does anybody know why it acts like this ? 有人知道为什么会这样吗? Thank you. 谢谢。

It should work if you add: 如果添加,它应该可以工作:

    constraints.weightx = (double) width / 7.0;
    constraints.weighty = (double) height / 7.0;

to your add method. 添加到您的添加方法。

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

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