gpt4 book ai didi

java - GridLayout 中心溢出组件

转载 作者:行者123 更新时间:2023-12-01 13:19:25 25 4
gpt4 key购买 nike

我有一组按钮。我的 JPanel 有 GridLayout 布局。我希望任何组件都在正方形之外才能居中。这是一张图片:http://screencast.com/t/z86ldR9vh

我希望“选项”按钮位于组下方的中心。

提前致谢!

最佳答案

为“选项”按钮创建另一个 JPanel 并将其设置为流布局。例如,假设顶部面板称为“panel1”,底部面板称为“panel2”:

// create top panel with first four buttons
JPanel panel1 = new JPanel(new GridLayout(2, 2));
panel1.add(new JButton("Play"));
panel1.add(new JButton("New Game"));
panel1.add(new JButton("Save Game"));
panel1.add(new JButton("Load Game"));

// create bottom panel with "Options" button
JPanel panel2 = new JPanel(new FlowLayout());
panel2.add(new JButton("Options"));

或者,如果您想要该类的完整代码(包含所有导入):

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;

public class Buttons {
public static void main(String[] args) {
Buttons gui = new Buttons();
}

public Buttons() {
// create frame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(250, 150));
frame.setLayout(new FlowLayout());
frame.setVisible(true);

// create top panel with first four buttons
JPanel panel1 = new JPanel(new GridLayout(2, 2));
panel1.add(new JButton("Play"));
panel1.add(new JButton("New Game"));
panel1.add(new JButton("Save Game"));
panel1.add(new JButton("Load Game"));

// create bottom panel with "Options" button
JPanel panel2 = new JPanel(new FlowLayout());
panel2.add(new JButton("Options"));

// add panels to frame
frame.add(panel1);
frame.add(panel2);
}
}

关于java - GridLayout 中心溢出组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22161911/

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