Reputation: 181
My JFrame
window always starts at the upper left corner. I want it to start in the middle of the screen. How can I solve this problem?
Upvotes: 0
Views: 396
Reputation: 431
Try this:
public static void centreWindow(Window frame) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
}
Upvotes: 0
Reputation: 27346
Use setBounds
to declare the window's x
and y
position, along with it's height
and width
, if you know the size
of the screen.
The other option is to use the frame.setLocationRelativeTo()
method, and pass in null
.
Upvotes: 2
Reputation: 1243
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
Source: How to set JFrame to appear centered, regardless of monitor resolution?
Upvotes: 0