gpt4 book ai didi

java - 无法使 Java GridBagConstraints 工作

转载 作者:行者123 更新时间:2023-11-30 05:52:02 27 4
gpt4 key购买 nike

为此苦苦挣扎了一段时间。我的方法如下所示:

public Frame(){
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);

JPanel panel = new JPanel(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight =3;
gbc.gridwidth = 3;


JButton upButt = new JButton();//Buttons.upButton();
gbc.gridx = 1;
gbc.gridy = 0;
panel.add(upButt, gbc);

JButton downButt = new JButton();
gbc.gridx = 1;
gbc.gridy = 2;
panel.add(downButt, gbc);

JButton leftButt = new JButton();//Buttons.leftButton();
gbc.gridx=0;
gbc.gridy = 1;
panel.add(leftButt, gbc);

JButton rightButt = new JButton();//Buttons.rightButton();
gbc.gridx =2;
gbc.gridy = 1;
panel.add(rightButt, gbc);

window.add(panel);
window.setVisible(true);

}

根据我的理解 - 在阅读和重读 Java 文档之后。 - 这应该给我 4 个十字形的按钮。然而,情况并非如此,按钮在窗口中央一个接一个地堆叠。我错过了什么?

最佳答案

为什么使用 gridheight 和 gridwidth 为 3?至少可以说这有点奇怪。

为了我的钱,我会简化事情并使用简单的 GridLayout:

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

public class Foo003 {
public static void main(String[] args) {
JButton upButton = new JButton("Up");
JButton downButton = new JButton("Down");
JButton leftButton = new JButton("Left");
JButton rightButton = new JButton("Right");
JComponent[][] components = {
{ new JLabel(), upButton, new JLabel() },
{ leftButton, new JLabel(), rightButton },
{ new JLabel(), downButton, new JLabel() } };

JPanel panel = new JPanel(new GridLayout(components.length,
components[0].length, 8, 8));
for (int i = 0; i < components.length; i++) {
for (int j = 0; j < components[i].length; j++) {
panel.add(components[i][j]);
}
}

int eb = 15;
panel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));

JFrame frame = new JFrame("Grid e.g.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

enter image description here

关于java - 无法使 Java GridBagConstraints 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12117970/

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