我无法将 Canvas 绘制在 JFrame
的中心。我的希望是在 JFrame
上绘制一个具有精美边框的图像,然后 Canvas
将位于 JFrame
的中心。我尝试过canvas.setLocation(Point p)和canvas.setBounds(矩形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 ,在问题空间里发帖太多了。
谢谢你的帮助
最佳答案
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 约束了解为什么这有效。
关于Java:重新定位绘制到 JFrame 中的 Canvas 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34241915/