Get the bounds (x, y, width, height) of the screen where the given component lies or "null" if not on any screen. - Java Swing

Java examples for Swing:JComponent

Description

Get the bounds (x, y, width, height) of the screen where the given component lies or "null" if not on any screen.

Demo Code


import java.awt.Component;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import org.apache.log4j.Logger;

public class Main{
    private static final Logger LOGGER = Logger
            .getLogger(GraphicsDeviceUtil.class);
    /**//www.j  a  v  a 2  s .c  om
     * Get the bounds (x, y, width, height) of the screen where the given
     * component lies or "null" if not on any screen.
     * 
     * @param component
     * @return
     */
    public static Rectangle getGraphicsDeviceBounds(Component component) {
        Rectangle componentBounds = component.getBounds();

        for (GraphicsDevice graphicsDevice : GraphicsEnvironment
                .getLocalGraphicsEnvironment().getScreenDevices()) {
            for (GraphicsConfiguration graphicsConfiguration : graphicsDevice
                    .getConfigurations()) {
                Rectangle graphicsDeviceBounds = graphicsConfiguration
                        .getBounds();

                if (componentBounds.x >= graphicsDeviceBounds.x
                        && componentBounds.x <= graphicsDeviceBounds.x
                                + graphicsDeviceBounds.width
                        && componentBounds.y >= graphicsDeviceBounds.y
                        && componentBounds.y <= graphicsDeviceBounds.y
                                + graphicsDeviceBounds.height) {
                    return graphicsDeviceBounds;
                }
            }
        }

        LOGGER.warn(String.format(
                "The given component %s is not on any screen!", component));
        return null;
    }
}

Related Tutorials