Centers a JFrame on the screen and gives it the specified width and height - Java Swing

Java examples for Swing:JFrame

Description

Centers a JFrame on the screen and gives it the specified width and height

Demo Code


//package com.java2s;

import java.awt.Dimension;

import java.awt.Toolkit;

import javax.swing.JFrame;

public class Main {
    /**//from www.j a v  a2 s  .  c  o m
     * Centers a JFrame on the screen and gives it the specified width and
     * height
     * 
     * @param frame
     *            the frame to center
     * @param width
     *            the width of the frame
     * @param height
     *            the height of the frame
     */
    public static void centerFrame(JFrame frame, int width, int height) {
        frame.setSize(new Dimension(width, height));
        centerFrame(frame);
    }

    /**
     * Centers a JFrame on the screen
     * 
     * @param frame
     *            the frame to center
     */
    public static void centerFrame(JFrame frame) {
        Dimension frameSize = frame.getSize();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setBounds(screenSize.width / 2 - frameSize.width / 2,
                screenSize.height / 2 - frameSize.height / 2,
                frameSize.width, frameSize.height);
    }
}

Related Tutorials