Salman Ahmed
Salman Ahmed

Reputation: 181

Location of JFrame in middle of the window

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

Answers (4)

user508434
user508434

Reputation:

Another simple method:

frame.setLocationRelativeTo(null);

Upvotes: 1

sareeshmnair
sareeshmnair

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

christopher
christopher

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

bknopper
bknopper

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

Related Questions