gpt4 book ai didi

Java GridBagConstraints gridx 和 gridy 不工作?

转载 作者:行者123 更新时间:2023-11-29 06:06:24 26 4
gpt4 key购买 nike

我正在尝试使用 gridxgridy 约束来定位我的按钮。但它们不起作用!如果我更改 gridxgridy 变量,什么也不会发生。如果我将 fill to GridBagConstraints 更改为 NONE,它仍然不起作用。

我是不是漏掉了什么?

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

public class Window extends JFrame{
private static final long serialVersionUID = 1L;

JFrame frame = new JFrame("GUI");
JTextField username = new JTextField(20);

public void CreateWindow(){
JPanel pane = new JPanel();
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

c.fill = GridBagConstraints.NONE;

JButton button = new JButton("Button 1");
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 3; //Has no effect
c.gridy = 5; //Has no effect
c.anchor = GridBagConstraints.NORTHWEST;//If I remove this, it still does not work.
pane.add(button, c);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(400, 600);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.add(pane);
frame.setVisible(true);
}
}

如果这很难阅读,那就是问题所在:

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

c.fill = GridBagConstraints.NONE;

JButton button = new JButton("Button 1");
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 3; //Has no effect
c.gridy = 5; //Has no effect
c.anchor = GridBagConstraints.NORTHWEST; //If I remove this, it still does not work.
pane.add(button, c);

最佳答案

自从我完成 swing 布局以来已经有一段时间了,但是如果你的 JPanel 中有多个 JComponent,gridX 和 gridY 不会只有效果吗?看起来你只有一个 JButton,所以 GridBagLayout 没有任何布局要做。

关于Java GridBagConstraints gridx 和 gridy 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8401367/

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