Java Desktop centerOnDesktop(Component comp, Component parent, boolean bAdjust)

Here you can find the source of centerOnDesktop(Component comp, Component parent, boolean bAdjust)

Description

Centers a child window or dialog on a JDesktopPane.

License

Open Source License

Parameter

Parameter Description
bAdjust if true, ensure that location >= (0,0)

Declaration

public static void centerOnDesktop(Component comp, Component parent, boolean bAdjust) 

Method Source Code


//package com.java2s;
//it under the terms of the GNU Affero General Public License as published by

import java.awt.Component;

import java.awt.Dimension;

import java.awt.Point;

import javax.swing.JDesktopPane;

import javax.swing.JViewport;

public class Main {
    /**/*from  w w  w  . ja v a2 s.  c  o m*/
     * Centers a child window or dialog on a JDesktopPane.
     * If the given parent component is not a JDesktop pane, the generic center method is used.
     * @param bAdjust if true, ensure that location >= (0,0)
     */
    public static void centerOnDesktop(Component comp, Component parent, boolean bAdjust) {
        if (!(parent instanceof JDesktopPane)) {
            center(comp, parent, bAdjust);
        } else {
            JViewport jvp = (JViewport) parent.getParent();
            final Dimension dimParentSize = jvp.getSize();
            final Point pParentLocation = jvp.getViewPosition();

            placeComponent(comp, pParentLocation, dimParentSize, bAdjust);
        }
    }

    /**
     * Centers <code>comp</code> in <code>parent</code>. Useful for displaying subframes/dialogs.
     * For <code>Window</code>s, an alternative is to use Window.setLocationRelativeTo.
     * @param bAdjust if true, ensure that location >= (0,0)
     * todo: may be erroneous, when the "parent" is not really te parent component of comp, i.e. comp has not been added on parent.
     */
    public static void center(Component comp, Component parent, boolean bAdjust) {
        if (parent == null)
            return;

        final Dimension dimParentSize = parent.getSize();
        final Point pParentLocation = parent.getLocation();

        placeComponent(comp, pParentLocation, dimParentSize, bAdjust);
    }

    /**
     * Helper for center methods.
     * @param comp
     * @param pParentLocation
     * @param dimParentSize
     * @param bAdjust
     */
    private static void placeComponent(Component comp, Point pParentLocation, Dimension dimParentSize,
            boolean bAdjust) {
        final Dimension dimCompSize = comp.getSize();
        int x = pParentLocation.x + (dimParentSize.width - dimCompSize.width) / 2;
        int y = pParentLocation.y + (dimParentSize.height - dimCompSize.height) / 2;

        if (bAdjust) {
            x = Math.max(0, x);
            y = Math.max(0, y);
        }

        comp.setLocation(x, y);
    }
}

Related

  1. browse(File file, Component component)
  2. build(File appDir)
  3. openFile(String filePath)