java - GridLayout 中心溢出组件

标签 java components center

我有一组按钮。我的 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/

相关文章:

Java同步-IllegalMonitorStateException

java - 如何处理空参数的 JPA 查询方法中的所有枚举值

angular 2导出接口(interface)在组件内部初始化问题

wpf - 如何在 WPF 中的 DatePicker 中获取日历

css - 在 bootstrap .container 中将四个图像定位在同一个位置,以屏幕为中心

css - 如何在 li 中垂直居中 h1 和 span

java - log4j2 Web 查找不工作

java - 抛出 SQLIntegrityConstraintViolationException 时如何查找列和表名称

delphi - 如何正确发布从 'Loaded' 过程执行的事件?

html - 以 HTML 格式在屏幕上垂直居中链接