Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;

public class Main {
    public static void centerWindowOnScreen(Window aWindow) {
        Rectangle bounds = getScreenBounds(aWindow);
        Point p = new Point(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
        Dimension windowSize = aWindow.getSize();
        p.x -= windowSize.width / 2;
        p.y -= windowSize.height / 2;
        aWindow.setLocation(p);
    }

    private static Rectangle getScreenBounds(Window aWindow) {

        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] devices = ge.getScreenDevices();

        if (aWindow == null)
            return devices[0].getDefaultConfiguration().getBounds();

        Rectangle bounds = aWindow.getBounds();
        int centerX = (int) bounds.getCenterX();
        int centerY = (int) bounds.getCenterY();

        for (GraphicsDevice device : devices) {
            GraphicsConfiguration gc = device.getDefaultConfiguration();
            Rectangle rect = gc.getBounds();
            if (rect.contains(centerX, centerY))
                return rect;
        }

        return null;
    }
}