gpt4 book ai didi

Java GridBagLayout 内含组件

转载 作者:太空宇宙 更新时间:2023-11-04 08:24:35 25 4
gpt4 key购买 nike

我试图让带有两个面板的 GridBagLayout 分别占框架的 40% 和 60%,同时能够在其中包含组件,但这很麻烦。

当我没有将按钮放置在面板内时,它的工作方式就像我想要的那样。

不太确定我做错了什么,我尝试将按钮的创建移动到 GridBagLayout 上创建面板的位置,但它仍然不起作用。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test{

public void display(){
JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,650);
frame.setVisible(true);

JPanel test = new JPanel();
test.setLayout(new GridBagLayout());
GridBagConstraints c= new GridBagConstraints();

JPanel left= new JPanel();
JPanel right= new JPanel();

c.fill = GridBagConstraints.VERTICAL - GridBagConstraints.HORIZONTAL;
c.weightx = 0.4;
c.gridx = 1;
c.weighty = 1;
test.add(left,c);
c.weightx = .6;
c.gridx = 2;
test.add(right,c);

JButton button= new JButton("A button");
left.add(button,c);//If I do not add this, then it shows how I want it to be

frame.add(test);
}
}

最佳答案

权重的作用在于它们描述了如何处理额外的空间。组件具有布局管理器在计算布局时使用的首选尺寸、最小尺寸和最大尺寸。然后 GridBagLayout 使用这些权重分割额外的空间。在你的情况下,我认为分割的空间等于 900-button.getPreferredSize().width。您可能会将 800 个像素分割为 320 和 480 个像素。

关于Java GridBagLayout 内含组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8866891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com