繁体   English   中英

Java:重定位绘制到JFrame中的Canvas的问题

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

我无法在JFrame的中心绘制Canvas。 我希望将图像绘制到具有精美边框的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);

什么都不做。 完整的代码在这里 ,在一个问题的空间中张贴太多。

谢谢你的帮助

我无法在JFrame的中心绘制Canvas。

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

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

阅读有关如何使用GridBagLayout的Swing教程中所述的weightx / weighty 约束,以了解其工作原理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM