gpt4 book ai didi

java - 当我在 Java 中使用 GridBagLayout 时,按钮没有填充所有可用空间

转载 作者:行者123 更新时间:2023-11-30 03:40:45 25 4
gpt4 key购买 nike

我想创建一个应用程序,其按钮排列在不可见的表格中。即使我调整框架大小,按钮也应该填充假想单元格内的所有可用空间。我正在使用 Swing、GridBagLayout。我读过一些文章,解决方案是添加 .weightx=1.weighty=1Weightx 工作完美,它填补了空白,但 Weighty 却没有。按钮不会延伸到单元格的高度。我的代码有问题吗?或者需要添加一些内容来解决我的问题?或者我应该使用另一种布局?

public class NewClass {
public void NewClass(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1.0;

gbc.gridx = 0;
gbc.gridy = 0;
JButton B11 = new JButton("11");
panel.add(B11,gbc);

gbc.gridx = 1;
gbc.gridy = 0;
JButton B12 = new JButton("12");
panel.add(B12,gbc);

gbc.gridx = 0;
gbc.gridy = 1;
JButton B21 = new JButton("21");
panel.add(B21,gbc);

gbc.gridx = 1;
gbc.gridy = 1;
JButton B22 = new JButton("22");
panel.add(B22,gbc);

frame.pack();
frame.setSize(800,400);
frame.setVisible(true);
}}

最佳答案

您使用了错误的 GridBagConstraints#fill 字段值,因为您使用的值告诉布局管理器仅水平填充按钮。

你需要改变

  gbc.fill = GridBagConstraints.HORIZONTAL;

  // gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.BOTH;

如果您希望按钮填充两个方向(水平和垂直方向)。

关于java - 当我在 Java 中使用 GridBagLayout 时,按钮没有填充所有可用空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26873189/

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