Path: blob/master/src/java.desktop/share/classes/javax/swing/BoxLayout.java
41153 views
/*1* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/242526package javax.swing;2728import java.awt.*;29import java.beans.ConstructorProperties;30import java.io.Serializable;31import java.io.PrintStream;3233/**34* A layout manager that allows multiple components to be laid out either35* vertically or horizontally. The components will not wrap so, for36* example, a vertical arrangement of components will stay vertically37* arranged when the frame is resized.38* <div style="float:right;text-align:center">39* <p><b>Example:</b>40* <p><img src="doc-files/BoxLayout-1.gif"41* alt="The following text describes this graphic."42* width="191" height="201">43* </div>44* <p>45* Nesting multiple panels with different combinations of horizontal and46* vertical gives an effect similar to GridBagLayout, without the47* complexity. The diagram shows two panels arranged horizontally, each48* of which contains 3 components arranged vertically.49*50* <p> The BoxLayout manager is constructed with an axis parameter that51* specifies the type of layout that will be done. There are four choices:52*53* <blockquote><b>{@code X_AXIS}</b> - Components are laid out horizontally54* from left to right.</blockquote>55*56* <blockquote><b>{@code Y_AXIS}</b> - Components are laid out vertically57* from top to bottom.</blockquote>58*59* <blockquote><b>{@code LINE_AXIS}</b> - Components are laid out the way60* words are laid out in a line, based on the container's61* {@code ComponentOrientation} property. If the container's62* {@code ComponentOrientation} is horizontal then components are laid out63* horizontally, otherwise they are laid out vertically. For horizontal64* orientations, if the container's {@code ComponentOrientation} is left to65* right then components are laid out left to right, otherwise they are laid66* out right to left. For vertical orientations components are always laid out67* from top to bottom.</blockquote>68*69* <blockquote><b>{@code PAGE_AXIS}</b> - Components are laid out the way70* text lines are laid out on a page, based on the container's71* {@code ComponentOrientation} property. If the container's72* {@code ComponentOrientation} is horizontal then components are laid out73* vertically, otherwise they are laid out horizontally. For horizontal74* orientations, if the container's {@code ComponentOrientation} is left to75* right then components are laid out left to right, otherwise they are laid76* out right to left. For vertical orientations components are always77* laid out from top to bottom.</blockquote>78* <p>79* For all directions, components are arranged in the same order as they were80* added to the container.81* <p>82* BoxLayout attempts to arrange components83* at their preferred widths (for horizontal layout)84* or heights (for vertical layout).85* For a horizontal layout,86* if not all the components are the same height,87* BoxLayout attempts to make all the components88* as high as the highest component.89* If that's not possible for a particular component,90* then BoxLayout aligns that component vertically,91* according to the component's Y alignment.92* By default, a component has a Y alignment of 0.5,93* which means that the vertical center of the component94* should have the same Y coordinate as95* the vertical centers of other components with 0.5 Y alignment.96* <p>97* Similarly, for a vertical layout,98* BoxLayout attempts to make all components in the column99* as wide as the widest component.100* If that fails, it aligns them horizontally101* according to their X alignments. For {@code PAGE_AXIS} layout,102* horizontal alignment is done based on the leading edge of the component.103* In other words, an X alignment value of 0.0 means the left edge of a104* component if the container's {@code ComponentOrientation} is left to105* right and it means the right edge of the component otherwise.106* <p>107* Instead of using BoxLayout directly, many programs use the Box class.108* The Box class is a lightweight container that uses a BoxLayout.109* It also provides handy methods to help you use BoxLayout well.110* Adding components to multiple nested boxes is a powerful way to get111* the arrangement you want.112* <p>113* For further information and examples see114* <a115href="https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html">How to Use BoxLayout</a>,116* a section in <em>The Java Tutorial.</em>117* <p>118* <strong>Warning:</strong>119* Serialized objects of this class will not be compatible with120* future Swing releases. The current serialization support is121* appropriate for short term storage or RMI between applications running122* the same version of Swing. As of 1.4, support for long term storage123* of all JavaBeans124* has been added to the {@code java.beans} package.125* Please see {@link java.beans.XMLEncoder}.126*127* @see Box128* @see java.awt.ComponentOrientation129* @see JComponent#getAlignmentX130* @see JComponent#getAlignmentY131*132* @author Timothy Prinzing133* @since 1.2134*/135@SuppressWarnings("serial")136public class BoxLayout implements LayoutManager2, Serializable {137138/**139* Specifies that components should be laid out left to right.140*/141public static final int X_AXIS = 0;142143/**144* Specifies that components should be laid out top to bottom.145*/146public static final int Y_AXIS = 1;147148/**149* Specifies that components should be laid out in the direction of150* a line of text as determined by the target container's151* {@code ComponentOrientation} property.152*/153public static final int LINE_AXIS = 2;154155/**156* Specifies that components should be laid out in the direction that157* lines flow across a page as determined by the target container's158* {@code ComponentOrientation} property.159*/160public static final int PAGE_AXIS = 3;161162/**163* Creates a layout manager that will lay out components along the164* given axis.165*166* @param target the container that needs to be laid out167* @param axis the axis to lay out components along. Can be one of:168* {@code BoxLayout.X_AXIS, BoxLayout.Y_AXIS,169* BoxLayout.LINE_AXIS} or {@code BoxLayout.PAGE_AXIS}170*171* @exception AWTError if the value of {@code axis} is invalid172*/173@ConstructorProperties({"target", "axis"})174public BoxLayout(Container target, int axis) {175if (axis != X_AXIS && axis != Y_AXIS &&176axis != LINE_AXIS && axis != PAGE_AXIS) {177throw new AWTError("Invalid axis");178}179this.axis = axis;180this.target = target;181}182183/**184* Constructs a BoxLayout that185* produces debugging messages.186*187* @param target the container that needs to be laid out188* @param axis the axis to lay out components along. Can be one of:189* {@code BoxLayout.X_AXIS, BoxLayout.Y_AXIS,190* BoxLayout.LINE_AXIS} or {@code BoxLayout.PAGE_AXIS}191*192* @param dbg the stream to which debugging messages should be sent,193* null if none194*/195BoxLayout(Container target, int axis, PrintStream dbg) {196this(target, axis);197this.dbg = dbg;198}199200/**201* Returns the container that uses this layout manager.202*203* @return the container that uses this layout manager204*205* @since 1.6206*/207public final Container getTarget() {208return this.target;209}210211/**212* Returns the axis that was used to lay out components.213* Returns one of:214* {@code BoxLayout.X_AXIS, BoxLayout.Y_AXIS,215* BoxLayout.LINE_AXIS} or {@code BoxLayout.PAGE_AXIS}216*217* @return the axis that was used to lay out components218*219* @since 1.6220*/221public final int getAxis() {222return this.axis;223}224225/**226* Indicates that a child has changed its layout related information,227* and thus any cached calculations should be flushed.228* <p>229* This method is called by AWT when the invalidate method is called230* on the Container. Since the invalidate method may be called231* asynchronously to the event thread, this method may be called232* asynchronously.233*234* @param target the affected container235*236* @exception AWTError if the target isn't the container specified to the237* BoxLayout constructor238*/239public synchronized void invalidateLayout(Container target) {240checkContainer(target);241xChildren = null;242yChildren = null;243xTotal = null;244yTotal = null;245}246247/**248* Not used by this class.249*250* @param name the name of the component251* @param comp the component252*/253public void addLayoutComponent(String name, Component comp) {254invalidateLayout(comp.getParent());255}256257/**258* Not used by this class.259*260* @param comp the component261*/262public void removeLayoutComponent(Component comp) {263invalidateLayout(comp.getParent());264}265266/**267* Not used by this class.268*269* @param comp the component270* @param constraints constraints271*/272public void addLayoutComponent(Component comp, Object constraints) {273invalidateLayout(comp.getParent());274}275276/**277* Returns the preferred dimensions for this layout, given the components278* in the specified target container.279*280* @param target the container that needs to be laid out281* @return the dimensions >= 0 && <= Integer.MAX_VALUE282* @exception AWTError if the target isn't the container specified to the283* BoxLayout constructor284* @see Container285* @see #minimumLayoutSize286* @see #maximumLayoutSize287*/288public Dimension preferredLayoutSize(Container target) {289Dimension size;290synchronized(this) {291checkContainer(target);292checkRequests();293size = new Dimension(xTotal.preferred, yTotal.preferred);294}295296Insets insets = target.getInsets();297size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);298size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);299return size;300}301302/**303* Returns the minimum dimensions needed to lay out the components304* contained in the specified target container.305*306* @param target the container that needs to be laid out307* @return the dimensions >= 0 && <= Integer.MAX_VALUE308* @exception AWTError if the target isn't the container specified to the309* BoxLayout constructor310* @see #preferredLayoutSize311* @see #maximumLayoutSize312*/313public Dimension minimumLayoutSize(Container target) {314Dimension size;315synchronized(this) {316checkContainer(target);317checkRequests();318size = new Dimension(xTotal.minimum, yTotal.minimum);319}320321Insets insets = target.getInsets();322size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);323size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);324return size;325}326327/**328* Returns the maximum dimensions the target container can use329* to lay out the components it contains.330*331* @param target the container that needs to be laid out332* @return the dimensions >= 0 && <= Integer.MAX_VALUE333* @exception AWTError if the target isn't the container specified to the334* BoxLayout constructor335* @see #preferredLayoutSize336* @see #minimumLayoutSize337*/338public Dimension maximumLayoutSize(Container target) {339Dimension size;340synchronized(this) {341checkContainer(target);342checkRequests();343size = new Dimension(xTotal.maximum, yTotal.maximum);344}345346Insets insets = target.getInsets();347size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);348size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);349return size;350}351352/**353* Returns the alignment along the X axis for the container.354* If the box is horizontal, the default355* alignment will be returned. Otherwise, the alignment needed356* to place the children along the X axis will be returned.357*358* @param target the container359* @return the alignment >= 0.0f && <= 1.0f360* @exception AWTError if the target isn't the container specified to the361* BoxLayout constructor362*/363public synchronized float getLayoutAlignmentX(Container target) {364checkContainer(target);365checkRequests();366return xTotal.alignment;367}368369/**370* Returns the alignment along the Y axis for the container.371* If the box is vertical, the default372* alignment will be returned. Otherwise, the alignment needed373* to place the children along the Y axis will be returned.374*375* @param target the container376* @return the alignment >= 0.0f && <= 1.0f377* @exception AWTError if the target isn't the container specified to the378* BoxLayout constructor379*/380public synchronized float getLayoutAlignmentY(Container target) {381checkContainer(target);382checkRequests();383return yTotal.alignment;384}385386/**387* Called by the AWT <!-- XXX CHECK! --> when the specified container388* needs to be laid out.389*390* @param target the container to lay out391*392* @exception AWTError if the target isn't the container specified to the393* BoxLayout constructor394*/395public void layoutContainer(Container target) {396checkContainer(target);397int nChildren = target.getComponentCount();398int[] xOffsets = new int[nChildren];399int[] xSpans = new int[nChildren];400int[] yOffsets = new int[nChildren];401int[] ySpans = new int[nChildren];402403Dimension alloc = target.getSize();404Insets in = target.getInsets();405alloc.width -= in.left + in.right;406alloc.height -= in.top + in.bottom;407408// Resolve axis to an absolute value (either X_AXIS or Y_AXIS)409ComponentOrientation o = target.getComponentOrientation();410int absoluteAxis = resolveAxis( axis, o );411boolean ltr = (absoluteAxis != axis) ? o.isLeftToRight() : true;412413414// determine the child placements415synchronized(this) {416checkRequests();417418if (absoluteAxis == X_AXIS) {419SizeRequirements.calculateTiledPositions(alloc.width, xTotal,420xChildren, xOffsets,421xSpans, ltr);422SizeRequirements.calculateAlignedPositions(alloc.height, yTotal,423yChildren, yOffsets,424ySpans);425} else {426SizeRequirements.calculateAlignedPositions(alloc.width, xTotal,427xChildren, xOffsets,428xSpans, ltr);429SizeRequirements.calculateTiledPositions(alloc.height, yTotal,430yChildren, yOffsets,431ySpans);432}433}434435// flush changes to the container436for (int i = 0; i < nChildren; i++) {437Component c = target.getComponent(i);438c.setBounds((int) Math.min((long) in.left + (long) xOffsets[i], Integer.MAX_VALUE),439(int) Math.min((long) in.top + (long) yOffsets[i], Integer.MAX_VALUE),440xSpans[i], ySpans[i]);441442}443if (dbg != null) {444for (int i = 0; i < nChildren; i++) {445Component c = target.getComponent(i);446dbg.println(c.toString());447dbg.println("X: " + xChildren[i]);448dbg.println("Y: " + yChildren[i]);449}450}451452}453454void checkContainer(Container target) {455if (this.target != target) {456throw new AWTError("BoxLayout can't be shared");457}458}459460void checkRequests() {461if (xChildren == null || yChildren == null) {462// The requests have been invalidated... recalculate463// the request information.464int n = target.getComponentCount();465xChildren = new SizeRequirements[n];466yChildren = new SizeRequirements[n];467for (int i = 0; i < n; i++) {468Component c = target.getComponent(i);469if (!c.isVisible()) {470xChildren[i] = new SizeRequirements(0,0,0, c.getAlignmentX());471yChildren[i] = new SizeRequirements(0,0,0, c.getAlignmentY());472continue;473}474Dimension min = c.getMinimumSize();475Dimension typ = c.getPreferredSize();476Dimension max = c.getMaximumSize();477xChildren[i] = new SizeRequirements(min.width, typ.width,478max.width,479c.getAlignmentX());480yChildren[i] = new SizeRequirements(min.height, typ.height,481max.height,482c.getAlignmentY());483}484485// Resolve axis to an absolute value (either X_AXIS or Y_AXIS)486int absoluteAxis = resolveAxis(axis,target.getComponentOrientation());487488if (absoluteAxis == X_AXIS) {489xTotal = SizeRequirements.getTiledSizeRequirements(xChildren);490yTotal = SizeRequirements.getAlignedSizeRequirements(yChildren);491} else {492xTotal = SizeRequirements.getAlignedSizeRequirements(xChildren);493yTotal = SizeRequirements.getTiledSizeRequirements(yChildren);494}495}496}497498/**499* Given one of the 4 axis values, resolve it to an absolute axis.500* The relative axis values, PAGE_AXIS and LINE_AXIS are converted501* to their absolute couterpart given the target's ComponentOrientation502* value. The absolute axes, X_AXIS and Y_AXIS are returned unmodified.503*504* @param axis the axis to resolve505* @param o the ComponentOrientation to resolve against506* @return the resolved axis507*/508private int resolveAxis( int axis, ComponentOrientation o ) {509int absoluteAxis;510if( axis == LINE_AXIS ) {511absoluteAxis = o.isHorizontal() ? X_AXIS : Y_AXIS;512} else if( axis == PAGE_AXIS ) {513absoluteAxis = o.isHorizontal() ? Y_AXIS : X_AXIS;514} else {515absoluteAxis = axis;516}517return absoluteAxis;518}519520521private int axis;522private Container target;523524private transient SizeRequirements[] xChildren;525private transient SizeRequirements[] yChildren;526private transient SizeRequirements xTotal;527private transient SizeRequirements yTotal;528529private transient PrintStream dbg;530}531532533