Reputation: 1099
I can't get my Canvas to be drawn in the centre of my JFrame
. My hope is to draw an image to the JFrame
that will have a fancy border, then the Canvas
will sit in the centre of the JFrame
. I've tried canvas.setLocation(Point p)
and canvas.setBounds(Rectangle r)
and Canvas.setLocation(int x, int y)
and I can't get any of them to work. I also tried the following before calling game.frame.pack()
:
game.frame.setLayout(new BorderLayout());
game.frame.add(game, BorderLayout.CENTER);
This is the setup for the Canvas:
public Game() {
Dimension size = new Dimension((frameWidth * scale), frameHeight * scale);
setPreferredSize(size);
Game.game = this;
//draw game items
....
}
Then this is the JFrame
set up, which is done during the main method:
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();
Also tried this:
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);
Which does nothing. Full code is here, it is too much to post in the space of a question.
Thanks for you're help
Upvotes: 0
Views: 77
Reputation: 324147
I can't get my Canvas to be drawn in the centre of my JFrame.
The easiest way to do this is to use a GridBagLayout
instead of a BorderLayout
:
game.frame.setLayout(new GridBagLayout());
game.frame.add(game, new GridBagConstraints());
Read up on the weightx/weighty contraints as described in the Swing tutorial on How to Use GridBagLayout to understand why this works.
Upvotes: 2