Java GUI - 如何将单个按钮居中

The*_*heo 2 java

我对java很陌生(我已经习惯了python)。

注意:即使调整图形用户界面的大小,我确实希望该位置保持在中心。

我想知道如何使单个按钮居中?目前,该按钮位于 GUI 的顶部。

public class main_gui extends JFrame{

    public static void main(String[] args) {

        // Initial window
        JFrame start_frame = new JFrame("P.D");
        start_frame.setSize(1200, 800);
        start_frame.setVisible(true);
        start_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Panel to hold our buttons
        JPanel start_panel = new JPanel();
        start_frame.add(start_panel);


        // Button to initialize everything
        JButton start_button = new JButton("Start");
        // Take out the border around the text
        start_button.setFocusable(false);
        start_panel.add(start_button);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是当前的样子,我只想把这个按钮向下一点,放到中间。

在此输入图像描述

cam*_*ckr 5

不需要面板。只需将按钮直接添加到框架即可。

最简单的方法是使用GridBagLayout

frame.setLayout( new GridBagLayout() );
frame.add(startButton, new GridBagConstraints());
Run Code Online (Sandbox Code Playgroud)

默认情况下,组件将在GridBagLayout.