Java tutorial
//package com.java2s; //License from project: Apache License import java.awt.Dimension; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import java.awt.geom.Rectangle2D; public class Main { public static void centerOnScreenAtLocation(Window window, Point desiredLocation) { GraphicsDevice currentScreen = getCurrentScreen(desiredLocation, window.getSize()); Rectangle2D screenBounds = currentScreen.getDefaultConfiguration().getBounds(); window.setLocation((int) screenBounds.getCenterX() - (window.getWidth() / 2), (int) screenBounds.getCenterY() - (window.getHeight() / 2)); } public static GraphicsDevice getCurrentScreen(Window window) { return getCurrentScreen(window.getLocation(), window.getSize()); } public static GraphicsDevice getCurrentScreen(Point location, Dimension size) { GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); GraphicsDevice bestMatch = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); float bestPercentage = 0; for (GraphicsDevice device : devices) { Rectangle bounds = device.getDefaultConfiguration().getBounds(); float percentage = getPercentageOnScreen(location, size, bounds); if (percentage > bestPercentage) { bestMatch = device; bestPercentage = percentage; } } return bestMatch; } private static float getPercentageOnScreen(Point location, Dimension size, Rectangle screen) { Rectangle frameBounds = new Rectangle(location, size); Rectangle2D intersection = frameBounds.createIntersection(screen); int frameArea = size.width * size.height; int intersectionArea = (int) (intersection.getWidth() * intersection.getHeight()); float percentage = (float) intersectionArea / frameArea; return percentage < 0 ? 0 : percentage; } }