set c1 location relative to c2 - Java Swing

Java examples for Swing:JComponent

Description

set c1 location relative to c2

Demo Code


//package com.java2s;
import java.applet.Applet;

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

import java.awt.Dimension;

import java.awt.GraphicsEnvironment;

import java.awt.Point;
import java.awt.Rectangle;

import java.awt.Window;

public class Main {
    /**//from   w w  w .  j  ava2 s  .co m
     * set c1 location relative to c2
     * @param c1
     * @param c2
     */
    public static void setLocationRelativeTo(Component c1, Component c2) {
        Container root = null;

        if (c2 != null) {
            if (c2 instanceof Window || c2 instanceof Applet) {
                root = (Container) c2;
            } else {
                Container parent;
                for (parent = c2.getParent(); parent != null; parent = parent
                        .getParent()) {
                    if (parent instanceof Window
                            || parent instanceof Applet) {
                        root = parent;
                        break;
                    }
                }
            }
        }

        if ((c2 != null && !c2.isShowing()) || root == null
                || !root.isShowing()) {
            Dimension paneSize = c1.getSize();

            Point centerPoint = GraphicsEnvironment
                    .getLocalGraphicsEnvironment().getCenterPoint();
            c1.setLocation(centerPoint.x - paneSize.width / 2,
                    centerPoint.y - paneSize.height / 2);
        } else {
            Dimension invokerSize = c2.getSize();
            Point invokerScreenLocation = c2.getLocation(); // by longrm:
            // c2.getLocationOnScreen();

            Rectangle windowBounds = c1.getBounds();
            int dx = invokerScreenLocation.x
                    + ((invokerSize.width - windowBounds.width) >> 1);
            int dy = invokerScreenLocation.y
                    + ((invokerSize.height - windowBounds.height) >> 1);
            Rectangle ss = root.getGraphicsConfiguration().getBounds();

            // Adjust for bottom edge being offscreen
            if (dy + windowBounds.height > ss.y + ss.height) {
                dy = ss.y + ss.height - windowBounds.height;
                if (invokerScreenLocation.x - ss.x + invokerSize.width / 2 < ss.width / 2) {
                    dx = invokerScreenLocation.x + invokerSize.width;
                } else {
                    dx = invokerScreenLocation.x - windowBounds.width;
                }
            }

            // Avoid being placed off the edge of the screen
            if (dx + windowBounds.width > ss.x + ss.width) {
                dx = ss.x + ss.width - windowBounds.width;
            }
            if (dx < ss.x)
                dx = ss.x;
            if (dy < ss.y)
                dy = ss.y;

            c1.setLocation(dx, dy);
        }
    }
}

Related Tutorials