Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/javax/swing/BoxLayout.java
38829 views
/*1* Copyright (c) 1997, 2013, 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* <TABLE STYLE="FLOAT:RIGHT" BORDER="0" SUMMARY="layout">39* <TR>40* <TD ALIGN="CENTER">41* <P STYLE="TEXT-ALIGN:CENTER"><IMG SRC="doc-files/BoxLayout-1.gif"42* alt="The following text describes this graphic."43* WIDTH="191" HEIGHT="201" STYLE="FLOAT:BOTTOM; BORDER:0">44* </TD>45* </TR>46* </TABLE>47* <p>48* Nesting multiple panels with different combinations of horizontal and49* vertical gives an effect similar to GridBagLayout, without the50* complexity. The diagram shows two panels arranged horizontally, each51* of which contains 3 components arranged vertically.52*53* <p> The BoxLayout manager is constructed with an axis parameter that54* specifies the type of layout that will be done. There are four choices:55*56* <blockquote><b><tt>X_AXIS</tt></b> - Components are laid out horizontally57* from left to right.</blockquote>58*59* <blockquote><b><tt>Y_AXIS</tt></b> - Components are laid out vertically60* from top to bottom.</blockquote>61*62* <blockquote><b><tt>LINE_AXIS</tt></b> - Components are laid out the way63* words are laid out in a line, based on the container's64* <tt>ComponentOrientation</tt> property. If the container's65* <tt>ComponentOrientation</tt> is horizontal then components are laid out66* horizontally, otherwise they are laid out vertically. For horizontal67* orientations, if the container's <tt>ComponentOrientation</tt> is left to68* right then components are laid out left to right, otherwise they are laid69* out right to left. For vertical orientations components are always laid out70* from top to bottom.</blockquote>71*72* <blockquote><b><tt>PAGE_AXIS</tt></b> - Components are laid out the way73* text lines are laid out on a page, based on the container's74* <tt>ComponentOrientation</tt> property. If the container's75* <tt>ComponentOrientation</tt> is horizontal then components are laid out76* vertically, otherwise they are laid out horizontally. For horizontal77* orientations, if the container's <tt>ComponentOrientation</tt> is left to78* right then components are laid out left to right, otherwise they are laid79* out right to left. For vertical orientations components are always80* laid out from top to bottom.</blockquote>81* <p>82* For all directions, components are arranged in the same order as they were83* added to the container.84* <p>85* BoxLayout attempts to arrange components86* at their preferred widths (for horizontal layout)87* or heights (for vertical layout).88* For a horizontal layout,89* if not all the components are the same height,90* BoxLayout attempts to make all the components91* as high as the highest component.92* If that's not possible for a particular component,93* then BoxLayout aligns that component vertically,94* according to the component's Y alignment.95* By default, a component has a Y alignment of 0.5,96* which means that the vertical center of the component97* should have the same Y coordinate as98* the vertical centers of other components with 0.5 Y alignment.99* <p>100* Similarly, for a vertical layout,101* BoxLayout attempts to make all components in the column102* as wide as the widest component.103* If that fails, it aligns them horizontally104* according to their X alignments. For <code>PAGE_AXIS</code> layout,105* horizontal alignment is done based on the leading edge of the component.106* In other words, an X alignment value of 0.0 means the left edge of a107* component if the container's <code>ComponentOrientation</code> is left to108* right and it means the right edge of the component otherwise.109* <p>110* Instead of using BoxLayout directly, many programs use the Box class.111* The Box class is a lightweight container that uses a BoxLayout.112* It also provides handy methods to help you use BoxLayout well.113* Adding components to multiple nested boxes is a powerful way to get114* the arrangement you want.115* <p>116* For further information and examples see117* <a118href="https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html">How to Use BoxLayout</a>,119* a section in <em>The Java Tutorial.</em>120* <p>121* <strong>Warning:</strong>122* Serialized objects of this class will not be compatible with123* future Swing releases. The current serialization support is124* appropriate for short term storage or RMI between applications running125* the same version of Swing. As of 1.4, support for long term storage126* of all JavaBeans™127* has been added to the <code>java.beans</code> package.128* Please see {@link java.beans.XMLEncoder}.129*130* @see Box131* @see java.awt.ComponentOrientation132* @see JComponent#getAlignmentX133* @see JComponent#getAlignmentY134*135* @author Timothy Prinzing136*/137@SuppressWarnings("serial")138public class BoxLayout implements LayoutManager2, Serializable {139140/**141* Specifies that components should be laid out left to right.142*/143public static final int X_AXIS = 0;144145/**146* Specifies that components should be laid out top to bottom.147*/148public static final int Y_AXIS = 1;149150/**151* Specifies that components should be laid out in the direction of152* a line of text as determined by the target container's153* <code>ComponentOrientation</code> property.154*/155public static final int LINE_AXIS = 2;156157/**158* Specifies that components should be laid out in the direction that159* lines flow across a page as determined by the target container's160* <code>ComponentOrientation</code> property.161*/162public static final int PAGE_AXIS = 3;163164/**165* Creates a layout manager that will lay out components along the166* given axis.167*168* @param target the container that needs to be laid out169* @param axis the axis to lay out components along. Can be one of:170* <code>BoxLayout.X_AXIS</code>,171* <code>BoxLayout.Y_AXIS</code>,172* <code>BoxLayout.LINE_AXIS</code> or173* <code>BoxLayout.PAGE_AXIS</code>174*175* @exception AWTError if the value of <code>axis</code> is invalid176*/177@ConstructorProperties({"target", "axis"})178public BoxLayout(Container target, int axis) {179if (axis != X_AXIS && axis != Y_AXIS &&180axis != LINE_AXIS && axis != PAGE_AXIS) {181throw new AWTError("Invalid axis");182}183this.axis = axis;184this.target = target;185}186187/**188* Constructs a BoxLayout that189* produces debugging messages.190*191* @param target the container that needs to be laid out192* @param axis the axis to lay out components along. Can be one of:193* <code>BoxLayout.X_AXIS</code>,194* <code>BoxLayout.Y_AXIS</code>,195* <code>BoxLayout.LINE_AXIS</code> or196* <code>BoxLayout.PAGE_AXIS</code>197*198* @param dbg the stream to which debugging messages should be sent,199* null if none200*/201BoxLayout(Container target, int axis, PrintStream dbg) {202this(target, axis);203this.dbg = dbg;204}205206/**207* Returns the container that uses this layout manager.208*209* @return the container that uses this layout manager210*211* @since 1.6212*/213public final Container getTarget() {214return this.target;215}216217/**218* Returns the axis that was used to lay out components.219* Returns one of:220* <code>BoxLayout.X_AXIS</code>,221* <code>BoxLayout.Y_AXIS</code>,222* <code>BoxLayout.LINE_AXIS</code> or223* <code>BoxLayout.PAGE_AXIS</code>224*225* @return the axis that was used to lay out components226*227* @since 1.6228*/229public final int getAxis() {230return this.axis;231}232233/**234* Indicates that a child has changed its layout related information,235* and thus any cached calculations should be flushed.236* <p>237* This method is called by AWT when the invalidate method is called238* on the Container. Since the invalidate method may be called239* asynchronously to the event thread, this method may be called240* asynchronously.241*242* @param target the affected container243*244* @exception AWTError if the target isn't the container specified to the245* BoxLayout constructor246*/247public synchronized void invalidateLayout(Container target) {248checkContainer(target);249xChildren = null;250yChildren = null;251xTotal = null;252yTotal = null;253}254255/**256* Not used by this class.257*258* @param name the name of the component259* @param comp the component260*/261public void addLayoutComponent(String name, Component comp) {262invalidateLayout(comp.getParent());263}264265/**266* Not used by this class.267*268* @param comp the component269*/270public void removeLayoutComponent(Component comp) {271invalidateLayout(comp.getParent());272}273274/**275* Not used by this class.276*277* @param comp the component278* @param constraints constraints279*/280public void addLayoutComponent(Component comp, Object constraints) {281invalidateLayout(comp.getParent());282}283284/**285* Returns the preferred dimensions for this layout, given the components286* in the specified target container.287*288* @param target the container that needs to be laid out289* @return the dimensions >= 0 && <= Integer.MAX_VALUE290* @exception AWTError if the target isn't the container specified to the291* BoxLayout constructor292* @see Container293* @see #minimumLayoutSize294* @see #maximumLayoutSize295*/296public Dimension preferredLayoutSize(Container target) {297Dimension size;298synchronized(this) {299checkContainer(target);300checkRequests();301size = new Dimension(xTotal.preferred, yTotal.preferred);302}303304Insets insets = target.getInsets();305size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);306size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);307return size;308}309310/**311* Returns the minimum dimensions needed to lay out the components312* contained in the specified target container.313*314* @param target the container that needs to be laid out315* @return the dimensions >= 0 && <= Integer.MAX_VALUE316* @exception AWTError if the target isn't the container specified to the317* BoxLayout constructor318* @see #preferredLayoutSize319* @see #maximumLayoutSize320*/321public Dimension minimumLayoutSize(Container target) {322Dimension size;323synchronized(this) {324checkContainer(target);325checkRequests();326size = new Dimension(xTotal.minimum, yTotal.minimum);327}328329Insets insets = target.getInsets();330size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);331size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);332return size;333}334335/**336* Returns the maximum dimensions the target container can use337* to lay out the components it contains.338*339* @param target the container that needs to be laid out340* @return the dimensions >= 0 && <= Integer.MAX_VALUE341* @exception AWTError if the target isn't the container specified to the342* BoxLayout constructor343* @see #preferredLayoutSize344* @see #minimumLayoutSize345*/346public Dimension maximumLayoutSize(Container target) {347Dimension size;348synchronized(this) {349checkContainer(target);350checkRequests();351size = new Dimension(xTotal.maximum, yTotal.maximum);352}353354Insets insets = target.getInsets();355size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);356size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);357return size;358}359360/**361* Returns the alignment along the X axis for the container.362* If the box is horizontal, the default363* alignment will be returned. Otherwise, the alignment needed364* to place the children along the X axis will be returned.365*366* @param target the container367* @return the alignment >= 0.0f && <= 1.0f368* @exception AWTError if the target isn't the container specified to the369* BoxLayout constructor370*/371public synchronized float getLayoutAlignmentX(Container target) {372checkContainer(target);373checkRequests();374return xTotal.alignment;375}376377/**378* Returns the alignment along the Y axis for the container.379* If the box is vertical, the default380* alignment will be returned. Otherwise, the alignment needed381* to place the children along the Y axis will be returned.382*383* @param target the container384* @return the alignment >= 0.0f && <= 1.0f385* @exception AWTError if the target isn't the container specified to the386* BoxLayout constructor387*/388public synchronized float getLayoutAlignmentY(Container target) {389checkContainer(target);390checkRequests();391return yTotal.alignment;392}393394/**395* Called by the AWT <!-- XXX CHECK! --> when the specified container396* needs to be laid out.397*398* @param target the container to lay out399*400* @exception AWTError if the target isn't the container specified to the401* BoxLayout constructor402*/403public void layoutContainer(Container target) {404checkContainer(target);405int nChildren = target.getComponentCount();406int[] xOffsets = new int[nChildren];407int[] xSpans = new int[nChildren];408int[] yOffsets = new int[nChildren];409int[] ySpans = new int[nChildren];410411Dimension alloc = target.getSize();412Insets in = target.getInsets();413alloc.width -= in.left + in.right;414alloc.height -= in.top + in.bottom;415416// Resolve axis to an absolute value (either X_AXIS or Y_AXIS)417ComponentOrientation o = target.getComponentOrientation();418int absoluteAxis = resolveAxis( axis, o );419boolean ltr = (absoluteAxis != axis) ? o.isLeftToRight() : true;420421422// determine the child placements423synchronized(this) {424checkRequests();425426if (absoluteAxis == X_AXIS) {427SizeRequirements.calculateTiledPositions(alloc.width, xTotal,428xChildren, xOffsets,429xSpans, ltr);430SizeRequirements.calculateAlignedPositions(alloc.height, yTotal,431yChildren, yOffsets,432ySpans);433} else {434SizeRequirements.calculateAlignedPositions(alloc.width, xTotal,435xChildren, xOffsets,436xSpans, ltr);437SizeRequirements.calculateTiledPositions(alloc.height, yTotal,438yChildren, yOffsets,439ySpans);440}441}442443// flush changes to the container444for (int i = 0; i < nChildren; i++) {445Component c = target.getComponent(i);446c.setBounds((int) Math.min((long) in.left + (long) xOffsets[i], Integer.MAX_VALUE),447(int) Math.min((long) in.top + (long) yOffsets[i], Integer.MAX_VALUE),448xSpans[i], ySpans[i]);449450}451if (dbg != null) {452for (int i = 0; i < nChildren; i++) {453Component c = target.getComponent(i);454dbg.println(c.toString());455dbg.println("X: " + xChildren[i]);456dbg.println("Y: " + yChildren[i]);457}458}459460}461462void checkContainer(Container target) {463if (this.target != target) {464throw new AWTError("BoxLayout can't be shared");465}466}467468void checkRequests() {469if (xChildren == null || yChildren == null) {470// The requests have been invalidated... recalculate471// the request information.472int n = target.getComponentCount();473xChildren = new SizeRequirements[n];474yChildren = new SizeRequirements[n];475for (int i = 0; i < n; i++) {476Component c = target.getComponent(i);477if (!c.isVisible()) {478xChildren[i] = new SizeRequirements(0,0,0, c.getAlignmentX());479yChildren[i] = new SizeRequirements(0,0,0, c.getAlignmentY());480continue;481}482Dimension min = c.getMinimumSize();483Dimension typ = c.getPreferredSize();484Dimension max = c.getMaximumSize();485xChildren[i] = new SizeRequirements(min.width, typ.width,486max.width,487c.getAlignmentX());488yChildren[i] = new SizeRequirements(min.height, typ.height,489max.height,490c.getAlignmentY());491}492493// Resolve axis to an absolute value (either X_AXIS or Y_AXIS)494int absoluteAxis = resolveAxis(axis,target.getComponentOrientation());495496if (absoluteAxis == X_AXIS) {497xTotal = SizeRequirements.getTiledSizeRequirements(xChildren);498yTotal = SizeRequirements.getAlignedSizeRequirements(yChildren);499} else {500xTotal = SizeRequirements.getAlignedSizeRequirements(xChildren);501yTotal = SizeRequirements.getTiledSizeRequirements(yChildren);502}503}504}505506/**507* Given one of the 4 axis values, resolve it to an absolute axis.508* The relative axis values, PAGE_AXIS and LINE_AXIS are converted509* to their absolute couterpart given the target's ComponentOrientation510* value. The absolute axes, X_AXIS and Y_AXIS are returned unmodified.511*512* @param axis the axis to resolve513* @param o the ComponentOrientation to resolve against514* @return the resolved axis515*/516private int resolveAxis( int axis, ComponentOrientation o ) {517int absoluteAxis;518if( axis == LINE_AXIS ) {519absoluteAxis = o.isHorizontal() ? X_AXIS : Y_AXIS;520} else if( axis == PAGE_AXIS ) {521absoluteAxis = o.isHorizontal() ? Y_AXIS : X_AXIS;522} else {523absoluteAxis = axis;524}525return absoluteAxis;526}527528529private int axis;530private Container target;531532private transient SizeRequirements[] xChildren;533private transient SizeRequirements[] yChildren;534private transient SizeRequirements xTotal;535private transient SizeRequirements yTotal;536537private transient PrintStream dbg;538}539540541