如何居中 JPanel(包含 JBox,但不一定)?

How to center a JPanel (that contains a JBox, but not necessarily)?

我已经搜索了大约 2 个小时,并阅读了方法和教程,但由于某种原因,我的程序仍然没有按预期运行。

我想将包含一个框的面板放在屏幕中央,该框包含一些按钮。有一种方法可以用 RigidBox 做到这一点,但它被硬编码为我当前 window/screen 的大小,我想要一些无论从哪里打开都可以居中的东西。

    package layout;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;

import javax.swing.*;

public class Layout2 {

    public static void main(String[] args) {

        //The window that opens when you run the application
        JFrame mainWindow = new JFrame("Solitare Anca Version 2016");
        mainWindow.setSize(1000, 800);
        mainWindow.setLocation(460, 140);

        //The main menu bar, default in top left of the window it belongs to I think?
        JMenuBar mainMenu = new JMenuBar();
        //JMenu's=the menus in a bar
        JMenu file = new JMenu("Home");
        //Items in each menu
        JMenuItem save=new JMenuItem("Save progress");
        file.add(save);
        JMenuItem load=new JMenuItem("Load game");
        file.add(load);
        JMenuItem savexit=new JMenuItem("Save & exit");
        file.add(savexit);
        JMenuItem close=new JMenuItem("Close game");
        file.add(close);
        JMenu options = new JMenu("Options");
        JMenuItem changeback=new JMenuItem("Pick another card back");
        options.add(changeback);
        JMenuItem changecolor=new JMenuItem("Modify background color");
        options.add(changecolor);
        JMenuItem changelang=new JMenuItem("Change language");
        options.add(changelang);
        JMenuItem sound=new JMenuItem("Sound options");
        options.add(sound);
        JMenu help = new JMenu("Help");
        JMenuItem rules=new JMenuItem("Rules");
        help.add(rules);

        //Ading the menus to the bar
        mainMenu.add(file);
        mainMenu.add(options);
        mainMenu.add(help);

        JPanel content=new JPanel();

        JPanel butPan = new JPanel();
        butPan.setBackground(Color.BLACK);

        JButton okbut = new JButton("START THE GAME");
        JButton exitbut = new JButton("   EXIT   ");
        Box butBox=Box.createVerticalBox();
        butBox.add(okbut);
        butBox.add(exitbut);
        butPan.add(BorderLayout.SOUTH, butBox);


        //Set bg of the main window to the very familiar default green
        content.setBackground(Color.decode("#008001")); 
        content.add(BorderLayout.SOUTH,butPan);

        mainWindow.setJMenuBar(mainMenu);
        mainWindow.setContentPane(content);
        mainWindow.setVisible(true);

        // mainWindow.setContentPane(content);

    }

}

这里我只是尝试了不同的方法来移动那个该死的 panel/box 但它就是不动...

你可以试试:

mainWindow.setLocationRelativeTo(null);

当给定 null 作为参数时,会将您的 JFrame 置于屏幕中央。

还要确保在 更改框架大小或打包框架后调用此方法。

编辑:建议查看 Andrew Thompson 的答案以获得代码解决方案。

补充一下这个答案,LayoutManager 通常是解决 Swing 面板格式问题的答案。有几个不同的管理器(范围很广,通常为了功能性而牺牲简单性)。使用核心 Java/Swing,我建议学习 GridBagLayout (Javadoc)。它非常强大(如果同样冗长的话),并且可以让您创建几乎任何您想要的布局。在实际实践中,您可能会使用多个。

您可以了解有关 LayoutManager 的更多信息 here

这里有四种居中组件的方法:

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

class CenterComponent {

    public static JLabel getLabel(String text) {
        return getLabel(text, SwingConstants.LEFT);
    }

    public static JLabel getLabel(String text, int alignment) {
        JLabel l = new JLabel(text, alignment);
        l.setBorder(new LineBorder(Color.RED, 2));
        return l;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JPanel p = new JPanel(new GridLayout(2,2,4,4));
                p.setBackground(Color.black);
                p.setBorder(new EmptyBorder(4,4,4,4));

                JPanel border = new JPanel(new BorderLayout());
                border.add(getLabel(
                    "Border", SwingConstants.CENTER), BorderLayout.CENTER);
                p.add(border);

                JPanel gridbag = new JPanel(new GridBagLayout());
                gridbag.add(getLabel("GridBag"));
                p.add(gridbag);

                JPanel grid = new JPanel(new GridLayout());
                grid.add(getLabel("Grid", SwingConstants.CENTER));
                p.add(grid);

                // from @0verbose
                JPanel box = new JPanel();
                box.setLayout(new BoxLayout(box, BoxLayout.X_AXIS ));

                box.add(Box.createHorizontalGlue());
                box.add(getLabel("Box"));
                box.add(Box.createHorizontalGlue());
                p.add(box);

                JFrame f = new JFrame("Streeeetch me..");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setContentPane(p);
                f.pack();
                f.setLocationByPlatform(true);
                f.setVisible(true);
            }
        });
    }
}