This returns the "local" bounds of a component. - Java 2D Graphics

Java examples for 2D Graphics:Rectangle

Description

This returns the "local" bounds of a component.

Demo Code


//package com.java2s;
import java.awt.Container;
import java.awt.Insets;
import java.awt.Rectangle;

public class Main {
    /**// ww  w.  j a v  a 2s  .  c  om
     * This returns the "local" bounds of a component.  This does the
     * same calculation as the method of the same name in
     * SwingUtilities, but this doesn't create a new Rectangle, but
     * instead overwrites the one passed in. 
     *
     * @param bounds rectangle to modify with the given component's
     * bounds (will create new Rectangle if this is null)
     * @param c component to get the bounds from 
     *
     * @return convenience reference to the rectangle passed in (or
     * the created rectangle) */
    public static Rectangle getLocalBounds(Rectangle bounds, Container c) {

        // Create a new Rectangle only if necessary.
        if (bounds == null)
            bounds = new Rectangle();

        // Get the insets of the components.
        Insets insets = c.getInsets();

        // Set the origin to (0,0) and the width and height to those
        // of the given component. 
        bounds.setBounds(0, 0, c.getWidth() - (insets.left + insets.right),
                c.getHeight() - (insets.top + insets.bottom));

        // Return the given rectangle (or the created one if this was
        // necessary). 
        return bounds;
    }
}

Related Tutorials