java为什么我的两个JButton设置为1时会占用2个空格(gridwidth)?
我目前正在使用JavaSwing和GridBagLayout来尝试组织一些按钮。我遇到了一个问题,我的“cookieClick”和“shopButton”按钮占用了两个空间(gridx 0和1),首先,我将它们的网格x设置为1,并将权重x设置为1.0。任何帮助都会很好,谢谢
摇摆设置类
package com.jetbrains;
import javax.swing.*;
import java.awt.*;
public class GUI {
final int screenX = 1280, screenY = 720;
JFrame mainGui = new JFrame();
JPanel gamePanel = new JPanel();
JPanel shopPanel = new JPanel();
JButton userName = new JButton("a"); // this is the area for the user's username they input in
JButton cookieCounter = new JButton("b"); // this is the counter for how many cookies the user currently has
JButton cookieClick = new JButton("c"); // this is the label for the cookie we click on
JButton shopButton = new JButton("d"); // this takes us to the shop, probably some if statement and set visible etc.
GridBagConstraints gameLayout = new GridBagConstraints();
public void guiConfig() {
mainGui.setSize(screenX, screenY);
mainGui.setTitle("journey");
mainGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainGui.setResizable(false);
mainGui.setBackground(Color.WHITE);
mainGui.add(gamePanel);
gamePanel.setSize(screenX, screenY);
gamePanel.setLayout(new GridBagLayout());
}
public void labelPositioning() {
gameLayout.fill = GridBagConstraints.HORIZONTAL;
gameLayout.gridx = 0;
gameLayout.gridwidth = 2;
gameLayout.gridy = 0;
gameLayout.weightx = 2.0;
gameLayout.weighty = 1.0;
gamePanel.add(cookieCounter, gameLayout);
gameLayout.fill = GridBagConstraints.HORIZONTAL;
gameLayout.gridx = 2;
gameLayout.gridwidth = 1;
gameLayout.gridy = 0;
gameLayout.weightx = 1.0;
gameLayout.weighty = 1.0;
gamePanel.add(userName, gameLayout);
gameLayout.fill = GridBagConstraints.HORIZONTAL;
gameLayout.gridx = 1;
gameLayout.gridwidth = 1;
gameLayout.gridy = 1;
gameLayout.weightx = 1.0;
gameLayout.weighty = 1.0;
gamePanel.add(cookieClick, gameLayout);
gameLayout.fill = GridBagConstraints.HORIZONTAL;
gameLayout.gridx = 1;
gameLayout.gridwidth = 1;
gameLayout.gridy = 2;
gameLayout.weightx = 1.0;
gameLayout.weighty = 1.0;
gamePanel.add(shopButton, gameLayout);
}
public void frameVisibility() {
mainGui.setVisible(true);
}
}
主课
package com.jetbrains;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
GUI run = new GUI();
run.guiConfig();
run.labelPositioning();
run.frameVisibility();
}
}
# 1 楼答案
GridBagLayout
非常复杂,有时可以做你意想不到的事情。在本例中,GridBagLayout
正在折叠第一列,因为其中(技术上)没有任何内容,这使它“看起来”就像其他按钮也在两列之间填充,而它们不是例如。我在第一列(下一行)中添加了一个空的
JLabel
,并能够生成以下输出您需要记住,布局管理器使用组件的首选/min/max大小来确定单元的宽度和高度(以及其他约束),这将影响某些行/列的大小