Centering a JFrame, JWindow, or JDialog on the Screen - Java Swing

Java examples for Swing:JFrame

Description

Centering a JFrame, JWindow, or JDialog on the Screen

Demo Code

import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;

public class Main {
  public static void main(String[] argv) throws Exception {
    // Get the size of the screen
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

    JFrame window = null;/*from w  ww . j  av a  2  s.co m*/
    // Determine the new location of the window
    int w = window.getSize().width;
    int h = window.getSize().height;
    int x = (dim.width - w) / 2;
    int y = (dim.height - h) / 2;

    // Move the window
    window.setLocation(x, y);
  }
}

Related Tutorials