Centers passed JInternalFrame internal frame within its desktop area. - Java Swing

Java examples for Swing:JInternalFrame

Description

Centers passed JInternalFrame internal frame within its desktop area.

Demo Code


//package com.java2s;

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

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

import javax.swing.JInternalFrame;

public class Main {
    /**/*from   w w  w. j  ava 2 s. c o  m*/
     * Centers passed internal frame within its desktop area. If centering
     * would cause the title bar to go off the top of the screen then move the
     * window down.
     *
     * @param   frame   The internal frame to be centered.
     *
     * @throws IllegalArgumentException    If <TT>frame</TT> is <TT>null</TT>.
     */
    public static void centerWithinDesktop(JInternalFrame frame) {
        if (frame == null) {
            throw new IllegalArgumentException("null JInternalFrame passed");
        }
        final Container parent = frame.getDesktopPane();
        if (parent != null && parent.isVisible()) {
            center(frame, new Rectangle(new Point(0, 0), parent.getSize()));
        }
    }

    /**
     * Centers <CODE>wind</CODE> within the passed rectangle.
     *
     * @param   wind   The Window to be centered.
     * @param   rect   The rectangle (in screen coords) to center
     *               <CODE>wind</CODE> within.
     *
     * @throws IllegalArgumentException
     *     If <TT>Window</TT> or <TT>Rectangle</TT> is <TT>null</TT>.
     */
    private static void center(Component wind, Rectangle rect) {
        if (wind == null || rect == null) {
            throw new IllegalArgumentException(
                    "null Window or Rectangle passed");
        }
        Dimension windSize = wind.getSize();
        int x = ((rect.width - windSize.width) / 2) + rect.x;
        int y = ((rect.height - windSize.height) / 2) + rect.y;
        if (y < rect.y) {
            y = rect.y;
        }
        wind.setLocation(x, y);
    }
}

Related Tutorials