【问题标题】:Center a JPanel with layout GridLayout inside another JPanel在另一个 JPanel 中将具有布局 GridLayout 的 JPanel 居中
【发布时间】:2019-12-28 05:30:44
【问题描述】:

我正在尝试制作国际象棋游戏,并在尝试使用 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)

我现在得到的结果:

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

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

【问题讨论】:

标签: java swing jpanel layout-manager grid-layout


【解决方案1】:

background 是一个JPanel,其默认布局为FlowLayout,这是您的问题所在。

我会改变

public static JPanel background = new JPanel();

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

建议...

好的,所以建议。

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

【讨论】:

  • 好的,现在我明白了。这是因为 FlowLayout 是 JPanel 的默认设置,而 JFrame 是 BorderLayout。标记为答案,因为这解决了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-25
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多