3745 lines · 140.5 KB · Java
RawDownload
/* * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation.  Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */package javax.swing; import java.awt.Component;import java.awt.Container;import java.awt.Dimension;import java.awt.Insets;import java.awt.LayoutManager2;import java.util.*;import static java.awt.Component.BaselineResizeBehavior;import static javax.swing.LayoutStyle.ComponentPlacement;import static javax.swing.SwingConstants.HORIZONTAL;import static javax.swing.SwingConstants.VERTICAL; /** * {@code GroupLayout} is a {@code LayoutManager} that hierarchically * groups components in order to position them in a {@code Container}. * {@code GroupLayout} is intended for use by builders, but may be * hand-coded as well. * Grouping is done by instances of the {@link Group Group} class. {@code * GroupLayout} supports two types of groups. A sequential group * positions its child elements sequentially, one after another. A * parallel group aligns its child elements in one of four ways. * <p> * Each group may contain any number of elements, where an element is * a {@code Group}, {@code Component}, or gap. A gap can be thought * of as an invisible component with a minimum, preferred and maximum * size. In addition {@code GroupLayout} supports a preferred gap, * whose value comes from {@code LayoutStyle}. * <p> * Elements are similar to a spring. Each element has a range as * specified by a minimum, preferred and maximum.  Gaps have either a * developer-specified range, or a range determined by {@code * LayoutStyle}. The range for {@code Component}s is determined from * the {@code Component}'s {@code getMinimumSize}, {@code * getPreferredSize} and {@code getMaximumSize} methods. In addition, * when adding {@code Component}s you may specify a particular range * to use instead of that from the component. The range for a {@code * Group} is determined by the type of group. A {@code ParallelGroup}'s * range is the maximum of the ranges of its elements. A {@code * SequentialGroup}'s range is the sum of the ranges of its elements. * <p> * {@code GroupLayout} treats each axis independently.  That is, there * is a group representing the horizontal axis, and a group * representing the vertical axis.  The horizontal group is * responsible for determining the minimum, preferred and maximum size * along the horizontal axis as well as setting the x and width of the * components contained in it. The vertical group is responsible for * determining the minimum, preferred and maximum size along the * vertical axis as well as setting the y and height of the * components contained in it. Each {@code Component} must exist in both * a horizontal and vertical group, otherwise an {@code IllegalStateException} * is thrown during layout, or when the minimum, preferred or * maximum size is requested. * <p> * The following diagram shows a sequential group along the horizontal * axis. The sequential group contains three components. A parallel group * was used along the vertical axis. * <p align="center"> * <img src="doc-files/groupLayout.1.gif"> * <p> * To reinforce that each axis is treated independently the diagram shows * the range of each group and element along each axis. The * range of each component has been projected onto the axes, * and the groups are rendered in blue (horizontal) and red (vertical). * For readability there is a gap between each of the elements in the * sequential group. * <p> * The sequential group along the horizontal axis is rendered as a solid * blue line. Notice the sequential group is the sum of the children elements * it contains. * <p> * Along the vertical axis the parallel group is the maximum of the height * of each of the components. As all three components have the same height, * the parallel group has the same height. * <p> * The following diagram shows the same three components, but with the * parallel group along the horizontal axis and the sequential group along * the vertical axis. * <p> * <p align="center"> * <img src="doc-files/groupLayout.2.gif"> * <p> * As {@code c1} is the largest of the three components, the parallel * group is sized to {@code c1}. As {@code c2} and {@code c3} are smaller * than {@code c1} they are aligned based on the alignment specified * for the component (if specified) or the default alignment of the * parallel group. In the diagram {@code c2} and {@code c3} were created * with an alignment of {@code LEADING}. If the component orientation were * right-to-left then {@code c2} and {@code c3} would be positioned on * the opposite side. * <p> * The following diagram shows a sequential group along both the horizontal * and vertical axis. * <p align="center"> * <img src="doc-files/groupLayout.3.gif"> * <p> * {@code GroupLayout} provides the ability to insert gaps between * {@code Component}s. The size of the gap is determined by an * instance of {@code LayoutStyle}. This may be turned on using the * {@code setAutoCreateGaps} method.  Similarly, you may use * the {@code setAutoCreateContainerGaps} method to insert gaps * between components that touch the edge of the parent container and the * container. * <p> * The following builds a panel consisting of two labels in * one column, followed by two textfields in the next column: * <pre> *   JComponent panel = ...; *   GroupLayout layout = new GroupLayout(panel); *   panel.setLayout(layout); * *   // Turn on automatically adding gaps between components *   layout.setAutoCreateGaps(true); * *   // Turn on automatically creating gaps between components that touch *   // the edge of the container and the container. *   layout.setAutoCreateContainerGaps(true); * *   // Create a sequential group for the horizontal axis. * *   GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); * *   // The sequential group in turn contains two parallel groups. *   // One parallel group contains the labels, the other the text fields. *   // Putting the labels in a parallel group along the horizontal axis *   // positions them at the same x location. *   // *   // Variable indentation is used to reinforce the level of grouping. *   hGroup.addGroup(layout.createParallelGroup(). *            addComponent(label1).addComponent(label2)); *   hGroup.addGroup(layout.createParallelGroup(). *            addComponent(tf1).addComponent(tf2)); *   layout.setHorizontalGroup(hGroup); * *   // Create a sequential group for the vertical axis. *   GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); * *   // The sequential group contains two parallel groups that align *   // the contents along the baseline. The first parallel group contains *   // the first label and text field, and the second parallel group contains *   // the second label and text field. By using a sequential group *   // the labels and text fields are positioned vertically after one another. *   vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). *            addComponent(label1).addComponent(tf1)); *   vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). *            addComponent(label2).addComponent(tf2)); *   layout.setVerticalGroup(vGroup); * </pre> * <p> * When run the following is produced. * <p align="center"> * <img src="doc-files/groupLayout.example.png"> * <p> * This layout consists of the following. * <ul><li>The horizontal axis consists of a sequential group containing two *         parallel groups.  The first parallel group contains the labels, *         and the second parallel group contains the text fields. *     <li>The vertical axis consists of a sequential group *         containing two parallel groups.  The parallel groups are configured *         to align their components along the baseline. The first parallel *         group contains the first label and first text field, and *         the second group consists of the second label and second *         text field. * </ul> * There are a couple of things to notice in this code: * <ul> *   <li>You need not explicitly add the components to the container; this *       is indirectly done by using one of the {@code add} methods of *       {@code Group}. *   <li>The various {@code add} methods return *       the caller.  This allows for easy chaining of invocations.  For *       example, {@code group.addComponent(label1).addComponent(label2);} is *       equivalent to *       {@code group.addComponent(label1); group.addComponent(label2);}. *   <li>There are no public constructors for {@code Group}s; instead *       use the create methods of {@code GroupLayout}. * </ul> * * @author Tomas Pavek * @author Jan Stola * @author Scott Violet * @since 1.6 */public class GroupLayout implements LayoutManager2 {    // Used in size calculations    private static final int MIN_SIZE = 0;     private static final int PREF_SIZE = 1;     private static final int MAX_SIZE = 2;     // Used by prepare, indicates min, pref or max isn't going to be used.    private static final int SPECIFIC_SIZE = 3;     private static final int UNSET = Integer.MIN_VALUE;     /**     * Indicates the size from the component or gap should be used for a     * particular range value.     *     * @see Group     */    public static final int DEFAULT_SIZE = -1;     /**     * Indicates the preferred size from the component or gap should     * be used for a particular range value.     *     * @see Group     */    public static final int PREFERRED_SIZE = -2;     // Whether or not we automatically try and create the preferred    // padding between components.    private boolean autocreatePadding;     // Whether or not we automatically try and create the preferred    // padding between components the touch the edge of the container and    // the container.    private boolean autocreateContainerPadding;     /**     * Group responsible for layout along the horizontal axis.  This is NOT     * the user specified group, use getHorizontalGroup to dig that out.     */    private Group horizontalGroup;     /**     * Group responsible for layout along the vertical axis.  This is NOT     * the user specified group, use getVerticalGroup to dig that out.     */    private Group verticalGroup;     // Maps from Component to ComponentInfo.  This is used for tracking    // information specific to a Component.    private Map<Component,ComponentInfo> componentInfos;     // Container we're doing layout for.    private Container host;     // Used by areParallelSiblings, cached to avoid excessive garbage.    private Set<Spring> tmpParallelSet;     // Indicates Springs have changed in some way since last change.    private boolean springsChanged;     // Indicates invalidateLayout has been invoked.    private boolean isValid;     // Whether or not any preferred padding (or container padding) springs    // exist    private boolean hasPreferredPaddingSprings;     /**     * The LayoutStyle instance to use, if null the sharedInstance is used.     */    private LayoutStyle layoutStyle;     /**     * If true, components that are not visible are treated as though they     * aren't there.     */    private boolean honorsVisibility;      /**     * Enumeration of the possible ways {@code ParallelGroup} can align     * its children.     *     * @see #createParallelGroup(Alignment)     * @since 1.6     */    public enum Alignment {        /**         * Indicates the elements should be         * aligned to the origin.  For the horizontal axis with a left to         * right orientation this means aligned to the left edge. For the         * vertical axis leading means aligned to the top edge.         *         * @see #createParallelGroup(Alignment)         */        LEADING,         /**         * Indicates the elements should be aligned to the end of the         * region.  For the horizontal axis with a left to right         * orientation this means aligned to the right edge. For the         * vertical axis trailing means aligned to the bottom edge.         *         * @see #createParallelGroup(Alignment)         */        TRAILING,         /**         * Indicates the elements should be centered in         * the region.         *         * @see #createParallelGroup(Alignment)         */        CENTER,         /**         * Indicates the elements should be aligned along         * their baseline.         *         * @see #createParallelGroup(Alignment)         * @see #createBaselineGroup(boolean,boolean)         */        BASELINE    }      private static void checkSize(int min, int pref, int max,            boolean isComponentSpring) {        checkResizeType(min, isComponentSpring);        if (!isComponentSpring && pref < 0) {            throw new IllegalArgumentException("Pref must be >= 0");        } else if (isComponentSpring) {            checkResizeType(pref, true);        }        checkResizeType(max, isComponentSpring);        checkLessThan(min, pref);        checkLessThan(pref, max);    }     private static void checkResizeType(int type, boolean isComponentSpring) {        if (type < 0 && ((isComponentSpring && type != DEFAULT_SIZE &&                type != PREFERRED_SIZE) ||                (!isComponentSpring && type != PREFERRED_SIZE))) {            throw new IllegalArgumentException("Invalid size");        }    }     private static void checkLessThan(int min, int max) {        if (min >= 0 && max >= 0 && min > max) {            throw new IllegalArgumentException(                    "Following is not met: min<=pref<=max");        }    }     /**     * Creates a {@code GroupLayout} for the specified {@code Container}.     *     * @param host the {@code Container} the {@code GroupLayout} is     *        the {@code LayoutManager} for     * @throws IllegalArgumentException if host is {@code null}     */    public GroupLayout(Container host) {        if (host == null) {            throw new IllegalArgumentException("Container must be non-null");        }        honorsVisibility = true;        this.host = host;        setHorizontalGroup(createParallelGroup(Alignment.LEADING, true));        setVerticalGroup(createParallelGroup(Alignment.LEADING, true));        componentInfos = new HashMap<Component,ComponentInfo>();        tmpParallelSet = new HashSet<Spring>();    }     /**     * Sets whether component visiblity is considered when sizing and     * positioning components. A value of {@code true} indicates that     * non-visible components should not be treated as part of the     * layout. A value of {@code false} indicates that components should be     * positioned and sized regardless of visibility.     * <p>     * A value of {@code false} is useful when the visibility of components     * is dynamically adjusted and you don't want surrounding components and     * the sizing to change.     * <p>     * The specified value is used for components that do not have an     * explicit visibility specified.     * <p>     * The default is {@code true}.     *     * @param honorsVisibility whether component visiblity is considered when     *                         sizing and positioning components     * @see #setHonorsVisibility(Component,Boolean)     */    public void setHonorsVisibility(boolean honorsVisibility) {        if (this.honorsVisibility != honorsVisibility) {            this.honorsVisibility = honorsVisibility;            springsChanged = true;            isValid = false;            invalidateHost();        }    }     /**     * Returns whether component visiblity is considered when sizing and     * positioning components.     *     * @return whether component visiblity is considered when sizing and     *         positioning components     */    public boolean getHonorsVisibility() {        return honorsVisibility;    }     /**     * Sets whether the component's visiblity is considered for     * sizing and positioning. A value of {@code Boolean.TRUE}     * indicates that if {@code component} is not visible it should     * not be treated as part of the layout. A value of {@code false}     * indicates that {@code component} is positioned and sized     * regardless of it's visibility.  A value of {@code null}     * indicates the value specified by the single argument method {@code     * setHonorsVisibility} should be used.     * <p>     * If {@code component} is not a child of the {@code Container} this     * {@code GroupLayout} is managine, it will be added to the     * {@code Container}.     *     * @param component the component     * @param honorsVisibility whether {@code component}'s visiblity should be     *              considered for sizing and positioning     * @throws IllegalArgumentException if {@code component} is {@code null}     * @see #setHonorsVisibility(Component,Boolean)     */    public void setHonorsVisibility(Component component,            Boolean honorsVisibility) {        if (component == null) {            throw new IllegalArgumentException("Component must be non-null");        }        getComponentInfo(component).setHonorsVisibility(honorsVisibility);        springsChanged = true;        isValid = false;        invalidateHost();    }     /**     * Sets whether a gap between components should automatically be     * created.  For example, if this is {@code true} and you add two     * components to a {@code SequentialGroup} a gap between the     * two components is automatically be created.  The default is     * {@code false}.     *     * @param autoCreatePadding whether a gap between components is     *        automatically created     */    public void setAutoCreateGaps(boolean autoCreatePadding) {        if (this.autocreatePadding != autoCreatePadding) {            this.autocreatePadding = autoCreatePadding;            invalidateHost();        }    }     /**     * Returns {@code true} if gaps between components are automatically     * created.     *     * @return {@code true} if gaps between components are automatically     *         created     */    public boolean getAutoCreateGaps() {        return autocreatePadding;    }     /**     * Sets whether a gap between the container and components that     * touch the border of the container should automatically be     * created. The default is {@code false}.     *     * @param autoCreateContainerPadding whether a gap between the container and     *        components that touch the border of the container should     *        automatically be created     */    public void setAutoCreateContainerGaps(boolean autoCreateContainerPadding){        if (this.autocreateContainerPadding != autoCreateContainerPadding) {            this.autocreateContainerPadding = autoCreateContainerPadding;            horizontalGroup = createTopLevelGroup(getHorizontalGroup());            verticalGroup = createTopLevelGroup(getVerticalGroup());            invalidateHost();        }    } 

Lines 1–500 of 3745.