繁体   English   中英

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

[英]Center a JPanel with layout GridLayout inside another 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对象BoardGUI ,但是我确实尝试了以下两种方法,但结果都是负面的:

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

我现在得到的结果:

在此处输入图片说明

正如您所看到的,它不是垂直居中的,我想要的行为是它在框架上水平和垂直居中。

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

background是一个JPanel ,它具有FlowLayout的默认布局,这是您的问题的来源。

我会改变

public static JPanel background = new JPanel();

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

建议...

好的,所以建议。

  • 避免使用static ,尤其是当您只想从另一个类中的一个类访问信息时 - 有更好的方法来实现这一点,而不会紧密耦合您的代码
  • 避免setPreferredSize - 这不是定义自定义大小提示的推荐方式,而是覆盖getPreferredSize ,这可以防止其他人更改它。
  • 我不会设置background面板的preferredSize ,而是简单地使用EmptyBorderGridBagLayout的边距/插入支持

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM