Center a frame. - Java Swing

Java examples for Swing:JFrame

Description

Center a frame.

Demo Code


//package com.java2s;
import java.awt.Dimension;

import java.awt.Toolkit;
import java.awt.Window;

public class Main {
    private static final Toolkit DEFAULT_TOOLKIT = Toolkit
            .getDefaultToolkit();//from   w ww  .  j a  v  a2  s  .c o  m

    /**
     * Center a frame.
     *
     * @param window the frame to center.
     */
    public static void setFrameCentered(Window window) {
        Dimension screenSize = DEFAULT_TOOLKIT.getScreenSize();
        final int screenWidth = screenSize.width;
        final int screenHeight = screenSize.height;
        int posX = (screenWidth / 2) - (window.getWidth() / 2);
        int posY = (screenHeight / 2) - (window.getHeight() / 2);
        window.setBounds(posX, posY, window.getWidth(), window.getHeight());
    }
}

Related Tutorials