Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.awt.*;

public class Main {
    /**
     * Centers the {@link java.awt.Window} on the display
     *
     * @param window
     *         Window to center
     */
    public static void centerWindow(Window window) {
        Rectangle boundsOfAvailableSpace = getBoundsOfAvailableDisplaySpace(window);
        int offsetX = (boundsOfAvailableSpace.width - window.getWidth()) / 2;
        int offsetY = (boundsOfAvailableSpace.height - window.getHeight()) / 2;
        window.setLocation(offsetX, offsetY);
    }

    /**
     * Retrieves the bounds represents the available space on the Window's display that is not used up by things like
     * the task bar or dock.
     *
     * @param window
     *         The window to center
     * @return Bounds of the display's available space
     */
    public static Rectangle getBoundsOfAvailableDisplaySpace(Window window) {
        GraphicsConfiguration graphicsConfigToUse = window.getGraphicsConfiguration();
        // If the Window does not have a GraphicsConfiguration yet (perhaps when the Window is not set up yet) then use the default screen's GraphicsConfiguration.
        if (graphicsConfigToUse == null) {
            graphicsConfigToUse = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                    .getDefaultConfiguration();
        }
        Rectangle boundsOfEntireScreen = graphicsConfigToUse.getBounds();
        Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(graphicsConfigToUse);

        return new Rectangle(screenInsets.left, screenInsets.top,
                boundsOfEntireScreen.width - screenInsets.left - screenInsets.right,
                boundsOfEntireScreen.height - screenInsets.top - screenInsets.bottom);
    }
}