将具有布局GridLayout的JPanel居中放置在另一个JPanel中

我正在尝试制作国际象棋游戏,并且尝试在GUI上工作时遇到了以下问题: 我似乎无法将棋盘垂直居中放在JFrame上。 JPanel在水平方向上居中,但在垂直方向上居中,偏心。

使用GridLayout将面板添加到其容器并初始化框架的代码:

public class ChessGUI extends JFrame 
{
    private static final long serialVersionUID = 1L;

    private static Dimension appDimention = new Dimension(1000,600);

    public static JFrame frame = new JFrame("Chess");
    public static JPanel background = new JPanel();
    public static BoardGUI board = new BoardGUI();

    public static int width;
    public static int height;

    public static void createFrame() 
    {
        JFrame.setDefaultLookAndFeelDecorated(true);

        //Set stuff that JFrame needs
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);

        //Set stuff that JPanel needs
        background.setPreferredSize(appDimention);

        frame.getcontentPane().add(background);
        frame.pack();

        //This 'board' is my Chess Board JPanel which I can't seem to centre
        //'background' is a JPanel which is,as the name suggests,the background
        background.add(board);

        //Set the location of the JFrame and set it visible
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

BoardGUI

@SuppressWarnings("serial")
public class BoardGUI extends JPanel
{
    GridLayout chessBoard = new GridLayout(8,8);
    Dimension boardDims = new Dimension(500,500);

    public BoardGUI() 
    {
        this.setLayout(chessBoard);
        this.setBackground(Color.BLACK);
        this.setPreferredSize(boardDims);
    }
}

我实际上并没有在上面的代码中做任何事情来使BoardGUI对象居中,但是我确实尝试了以下两种方法,结果都是负面的:

background.add(board,JPanel.CENTER_ALLIGnmENT)
background.add(board,BorderLayout.CENTER)

我现在得到的结果:

将具有布局GridLayout的JPanel居中放置在另一个JPanel中

如您所见,它不是垂直居中,而我想要的行为是使其同时在框架上水平和垂直居中。

非常感谢我对我可能犯的任何错误的帮助或见解!谢谢!

WAGXZ 回答:将具有布局GridLayout的JPanel居中放置在另一个JPanel中

backgroundJPanel,其默认布局为FlowLayout,这是您的问题出处。

我会改变

public static JPanel background = new JPanel();

public static JPanel background = new JPanel(new GridBagLayout());

建议...

好的,建议。

  • 避免使用static,尤其是如果您只想从另一类中的一个类访问信息,那么-可以通过更好的方法来实现此目的,而这不会紧密耦合您的代码
  • 避免使用setPreferredSize-这不是定义自定义大小提示的推荐方法,而是覆盖getPreferredSize,这样可以防止其他人对其进行更改。
  • 我没有设置preferredSize面板的background,而是简单地使用EmptyBorderGridBagLayout的边距/插入支持
本文链接:https://www.f2er.com/2849886.html

大家都在问