Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;

import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;

import javax.swing.JDialog;

public class Main {
    /**
     * If the dialog has a parent, center the dialog on the parent.
     * Otherwise center it on the screen.
     *
     * @param dialog
     */
    public static void centerDialog(JDialog dialog, Component owner) {
        // note: can't rely on dialog.getParent, it will always return non-null!
        if (owner == null) {
            centerWindowOnScreen(dialog);
        } else {
            centerDialogInParent(dialog);
        }
    }

    public static void centerWindowOnScreen(Window window) {
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension screenSize = tk.getScreenSize();
        window.setLocation((int) (screenSize.getWidth() / 2 - window.getWidth() / 2),
                (int) (screenSize.getHeight() / 2 - window.getHeight() / 2));
    }

    /**
     * Sets the bounds for a dialog so it is centered over its parent.
     *
     * @param dialog
     * @deprecated use centerOnParent
     */
    public static void centerDialogInParent(JDialog dialog) {
        centerInParent(dialog);
    }

    /**
     * Centers a component on its parent.
     *
     * @param component
     */
    public static void centerInParent(Component component) {
        Container parent = component.getParent();
        if (parent != null) {
            Rectangle parentBounds = parent.getBounds();
            Rectangle dialogBounds = new Rectangle(
                    (int) (parentBounds.getMinX() + parentBounds.getWidth() / 2 - component.getWidth() / 2),
                    (int) (parentBounds.getMinY() + parentBounds.getHeight() / 2 - component.getHeight() / 2),
                    component.getWidth(), component.getHeight());
            //dialog.setBounds( dialogBounds );
            component.setLocation(dialogBounds.x, dialogBounds.y);
        }
    }
}