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

时间:2015-12-12 16:02:45

标签: java swing canvas jframe location

我无法将我的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设置,这在主方法中完成:

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,在问题空间发布太多了。

谢谢你的帮助

1 个答案:

答案 0 :(得分:2)

  

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

最简单的方法是使用GridBagLayout代替BorderLayout

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

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