Center a Frame, Window, or Dialog on the Screen in Java

Description

The following code shows how to center a Frame, Window, or Dialog on the Screen.

Example


/*from   w w w.j a v a  2  s.c  o m*/
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;

public class Main {
  public static void main(String[] argv) throws Exception {
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

    JFrame window = new JFrame();
    window.setSize(300,300);
    
    int w = window.getSize().width;
    int h = window.getSize().height;
    int x = (dim.width - w) / 2;
    int y = (dim.height - h) / 2;

    window.setLocation(x, y);

    window.setVisible(true);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Development »




Java Algorithms
Java Clipboard
Java Compiler
Java Desktop
Java Virtual Machine
Java Math
OS
Random
Java Robot
Java RuntimeMXBean
Java Timer
Java UUID
Java Internationalization