center On Parent - Java Swing

Java examples for Swing:JComponent

Description

center On Parent

Demo Code


import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dialog.ModalityType;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Main{
    public static void centerOnParent(Window win) {
        Container parent = win.getParent();

        if (parent != null) {
            Point parentPosition = parent.getLocationOnScreen();
            win.setLocation(//from  www .  j  a  v a2s .  co  m
                    parentPosition.x + (parent.getWidth() - win.getWidth())
                            / 2, parentPosition.y
                            + (parent.getHeight() - win.getHeight()) / 2);
        } else {
            centerOnScreen(win);
        }
    }
    public static void centerOnScreen(Window win) {
        Rectangle screenBounds = SwingUtils.getScreenSize(win);
        win.setBounds((int) (screenBounds.getWidth() - win.getWidth()) / 2,
                (int) (screenBounds.getHeight() - win.getHeight()) / 2,
                win.getWidth(), win.getHeight());
    }
    public static Rectangle getScreenSize(Window win) {
        Rectangle sb;
        if (win == null) {
            sb = GraphicsEnvironment.getLocalGraphicsEnvironment()
                    .getDefaultScreenDevice().getDefaultConfiguration()
                    .getBounds();
        } else {
            sb = win.getGraphicsConfiguration().getBounds();
        }
        return sb;
    }
}

Related Tutorials