Java:重新定位绘制到 JFrame 中的 Canvas 时出现问题

Java: issues relocating Canvas that's drawn into a JFrame

我无法让 Canvas 绘制在 JFrame 的中心。我希望在 JFrame 上画一个有花哨边框的图像,然后 Canvas 会位于 JFrame 的中心。我已经尝试了 canvas.setLocation(Point p)canvas.setBounds(Rectangle r) 以及 Canvas.setLocation(int x, int y) 但我无法让它们中的任何一个工作。在调用 game.frame.pack():

之前,我还尝试了以下操作
game.frame.setLayout(new BorderLayout());
game.frame.add(game, BorderLayout.CENTER);

这是 Canvas 的设置:

public Game() {
    Dimension size = new Dimension((frameWidth * scale), frameHeight * scale);
    setPreferredSize(size);
    Game.game = this;
    //draw game items
    ....
}

然后这是 JFrame 设置,这是在 main 方法期间完成的:

game = new Game();
    game.frame.setResizable(false);
    game.frame.setUndecorated(true); //Enable for full screen
    game.frame.setLayout(new BorderLayout()); //Doesn't work
    game.frame.add(game, BorderLayout.CENTER); //Doesn't work
    //game.frame.add(game); //Just calling this doesn't work
    game.frame.pack();
    game.frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    //Window listener exitListener
    ....

    game.frame.addWindowListener(exitListener);
    game.frame.setLocationRelativeTo(null);
    game.frame.setVisible(true);
    game.frame.requestFocus();
    game.start();

也试过这个:

    game = new Game();
    game.frame.setResizable(false);
    game.frame.setUndecorated(true); //Enable for full screen
    game.frame.setLayout(new GridBagLayout());
    game.frame.add(game, new GridBagConstraints());
    game.frame.pack();
    game.frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

什么都不做。完整代码为here,一道题space中post太多了

感谢您的帮助

I can't get my Canvas to be drawn in the centre of my JFrame.

最简单的方法是使用 GridBagLayout 而不是 BorderLayout:

game.frame.setLayout(new GridBagLayout());
game.frame.add(game, new GridBagConstraints());

阅读 How to Use GridBagLayout 上的 Swing 教程中描述的 weightx/weighty 约束,了解其工作原理。