【发布时间】: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