how-to

Window (swing) applications

How to center the window

When you create window (javax.swing.JFrame), it is shown in default position . For its centering you can use more techniques.

VARIANT 1

You can center it "manually":

public class Main {

  public static void main(String[] args) {

    Window window = new Window();
    
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ( ( screenSize.getWidth() - window.getWidth() ) / 2 );
    int y = (int) ( ( screenSize.getHeight() - window.getHeight() ) / 2 );
    window.setLocation( x, y );

    window.setVisible(true);
  }
}
NOTE: For this variant of the centering you must include following:
import java.awt.Dimension;
import java.awt.Toolkit;

VARIANT 2

Very nice technique is to call method java.awt.Window.setLocationRelativeTo() with null parameter. In this case is window placed at the center of the screen.

public class Main {

  public static void main(String[] args) {

    Window window = new Window();
    window.setLocationRelativeTo( null );
    window.setVisible(true);
  }
}