Search code examples
javaswingjframeposition

How to set JFrame to appear centered, regardless of monitor resolution?


While working with Java, I find it hard to position my main window in the center of the screen when I start the application.

Is there any way I can do that? It doesn't have to be vertically centered, horizontal alignment is the more important goal for me. But vertical alignment is also welcome.


Solution

  • I always did it in this way:

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
    

    where this is the JFrame involved.