Java Swing How to - Position the form in the center screen








Question

We would like to know how to position the form in the center screen.

Answer

import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
//from   w w w.  ja va2s.  co  m
import javax.swing.JFrame;

public class Main extends JFrame {
  public Main() {
    setSize(250, 200);
    centerFrame();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  private void centerFrame() {
    Dimension windowSize = getSize();
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    Point centerPoint = ge.getCenterPoint();

    int dx = centerPoint.x - windowSize.width / 2;
    int dy = centerPoint.y - windowSize.height / 2;
    setLocation(dx, dy);
  }

  public static void main(String[] args) {
    Main ex = new Main();
    ex.setVisible(true);
  }
}