Java tutorial
//package com.java2s; /** * Copyright 2011-2016 Three Crickets LLC. * <p> * The contents of this file are subject to the terms of the LGPL version 3.0: * http://www.gnu.org/copyleft/lesser.html * <p> * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly from Three Crickets * at http://threecrickets.com/ */ import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Window; public class Main { public static void center(Window window, double ratio) { Rectangle bounds = window.getGraphicsConfiguration().getBounds(); int width = bounds.width / 2; int height = bounds.height / 2; int centerX = (int) (bounds.x + bounds.width * ratio); int centerY = (int) (bounds.y + bounds.height * ratio); window.setLocation(centerX - width / 2, centerY - height / 2); window.setPreferredSize(new Dimension(width, height)); window.pack(); } public static void center(Window window) { window.pack(); Rectangle bounds = window.getGraphicsConfiguration().getBounds(); int width = window.getWidth(); int height = window.getHeight(); int centerX = bounds.x + bounds.width / 2; int centerY = bounds.y + bounds.height / 2; window.setLocation(centerX - width / 2, centerY - height / 2); window.setPreferredSize(new Dimension(width, height)); } }