【发布时间】:2015-12-13 00:49:06
【问题描述】:
我无法将 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);
这是画布的设置:
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,在问题的空间里发帖太多了。
感谢您的帮助
【问题讨论】:
-
为什么你的 Game 类至少没有扩展 JComponent?你的绘画方法在哪里?
-
@KrzysztofCichocki 游戏类扩展了
Canvas,我的绘画是通过游戏循环在渲染方法中完成的。这一切都由我的Screen班级处理 -
@AdminHydra,您再次发布了几行随机代码。如果没有看到代码在您的应用程序中如何使用的上下文,我们将无能为力。发布正确的
SSCCE。我们不知道你所有的变量代表什么。创建一个简单的面板并为 id 指定首选大小和背景颜色,然后使用 GridBagLayout 将面板添加到框架中。您将看到面板居中,这是概念验证。如果您的真实代码不起作用,那么您正在做一些我们不知道的事情。努力就是需要帮助。 -
Full code is here, it is too much to post in the space of a question- 你从来没有被要求提供完整的代码。我们不是来帮你调试的。简化问题由您自己决定,以便您了解自己在哪里犯了错误。
标签: java swing canvas jframe location