1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 
  27 package javax.swing;
  28 
  29 import java.awt.*;
  30 import java.beans.ConstructorProperties;
  31 import java.io.Serializable;
  32 import java.io.PrintStream;
  33 
  34 /**
  35  * A layout manager that allows multiple components to be laid out either
  36  * vertically or horizontally. The components will not wrap so, for
  37  * example, a vertical arrangement of components will stay vertically
  38  * arranged when the frame is resized.
  39  * <TABLE STYLE="FLOAT:RIGHT" BORDER="0" SUMMARY="layout">
  40  *    <TR>
  41  *      <TD style="text-align:center">
  42  *         <P STYLE="TEXT-ALIGN:CENTER"><IMG SRC="doc-files/BoxLayout-1.gif"
  43  *          alt="The following text describes this graphic."
  44  *          WIDTH="191" HEIGHT="201" STYLE="FLOAT:BOTTOM; BORDER:0">
  45  *      </TD>
  46  *    </TR>
  47  * </TABLE>
  48  * <p>
  49  * Nesting multiple panels with different combinations of horizontal and
  50  * vertical gives an effect similar to GridBagLayout, without the
  51  * complexity. The diagram shows two panels arranged horizontally, each
  52  * of which contains 3 components arranged vertically.
  53  *
  54  * <p> The BoxLayout manager is constructed with an axis parameter that
  55  * specifies the type of layout that will be done. There are four choices:
  56  *
  57  * <blockquote><b>{@code X_AXIS}</b> - Components are laid out horizontally
  58  * from left to right.</blockquote>
  59  *
  60  * <blockquote><b>{@code Y_AXIS}</b> - Components are laid out vertically
  61  * from top to bottom.</blockquote>
  62  *
  63  * <blockquote><b>{@code LINE_AXIS}</b> - Components are laid out the way
  64  * words are laid out in a line, based on the container's
  65  * {@code ComponentOrientation} property. If the container's
  66  * {@code ComponentOrientation} is horizontal then components are laid out
  67  * horizontally, otherwise they are laid out vertically.  For horizontal
  68  * orientations, if the container's {@code ComponentOrientation} is left to
  69  * right then components are laid out left to right, otherwise they are laid
  70  * out right to left. For vertical orientations components are always laid out
  71  * from top to bottom.</blockquote>
  72  *
  73  * <blockquote><b>{@code PAGE_AXIS}</b> - Components are laid out the way
  74  * text lines are laid out on a page, based on the container's
  75  * {@code ComponentOrientation} property. If the container's
  76  * {@code ComponentOrientation} is horizontal then components are laid out
  77  * vertically, otherwise they are laid out horizontally.  For horizontal
  78  * orientations, if the container's {@code ComponentOrientation} is left to
  79  * right then components are laid out left to right, otherwise they are laid
  80  * out right to left.&nbsp; For vertical orientations components are always
  81  * laid out from top to bottom.</blockquote>
  82  * <p>
  83  * For all directions, components are arranged in the same order as they were
  84  * added to the container.
  85  * <p>
  86  * BoxLayout attempts to arrange components
  87  * at their preferred widths (for horizontal layout)
  88  * or heights (for vertical layout).
  89  * For a horizontal layout,
  90  * if not all the components are the same height,
  91  * BoxLayout attempts to make all the components
  92  * as high as the highest component.
  93  * If that's not possible for a particular component,
  94  * then BoxLayout aligns that component vertically,
  95  * according to the component's Y alignment.
  96  * By default, a component has a Y alignment of 0.5,
  97  * which means that the vertical center of the component
  98  * should have the same Y coordinate as
  99  * the vertical centers of other components with 0.5 Y alignment.
 100  * <p>
 101  * Similarly, for a vertical layout,
 102  * BoxLayout attempts to make all components in the column
 103  * as wide as the widest component.
 104  * If that fails, it aligns them horizontally
 105  * according to their X alignments.  For {@code PAGE_AXIS} layout,
 106  * horizontal alignment is done based on the leading edge of the component.
 107  * In other words, an X alignment value of 0.0 means the left edge of a
 108  * component if the container's {@code ComponentOrientation} is left to
 109  * right and it means the right edge of the component otherwise.
 110  * <p>
 111  * Instead of using BoxLayout directly, many programs use the Box class.
 112  * The Box class is a lightweight container that uses a BoxLayout.
 113  * It also provides handy methods to help you use BoxLayout well.
 114  * Adding components to multiple nested boxes is a powerful way to get
 115  * the arrangement you want.
 116  * <p>
 117  * For further information and examples see
 118  * <a
 119  href="http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html">How to Use BoxLayout</a>,
 120  * a section in <em>The Java Tutorial.</em>
 121  * <p>
 122  * <strong>Warning:</strong>
 123  * Serialized objects of this class will not be compatible with
 124  * future Swing releases. The current serialization support is
 125  * appropriate for short term storage or RMI between applications running
 126  * the same version of Swing.  As of 1.4, support for long term storage
 127  * of all JavaBeans&trade;
 128  * has been added to the {@code java.beans} package.
 129  * Please see {@link java.beans.XMLEncoder}.
 130  *
 131  * @see Box
 132  * @see java.awt.ComponentOrientation
 133  * @see JComponent#getAlignmentX
 134  * @see JComponent#getAlignmentY
 135  *
 136  * @author   Timothy Prinzing
 137  * @since 1.2
 138  */
 139 @SuppressWarnings("serial")
 140 public class BoxLayout implements LayoutManager2, Serializable {
 141 
 142     /**
 143      * Specifies that components should be laid out left to right.
 144      */
 145     public static final int X_AXIS = 0;
 146 
 147     /**
 148      * Specifies that components should be laid out top to bottom.
 149      */
 150     public static final int Y_AXIS = 1;
 151 
 152     /**
 153      * Specifies that components should be laid out in the direction of
 154      * a line of text as determined by the target container's
 155      * {@code ComponentOrientation} property.
 156      */
 157     public static final int LINE_AXIS = 2;
 158 
 159     /**
 160      * Specifies that components should be laid out in the direction that
 161      * lines flow across a page as determined by the target container's
 162      * {@code ComponentOrientation} property.
 163      */
 164     public static final int PAGE_AXIS = 3;
 165 
 166     /**
 167      * Creates a layout manager that will lay out components along the
 168      * given axis.
 169      *
 170      * @param target  the container that needs to be laid out
 171      * @param axis  the axis to lay out components along. Can be one of:
 172      *              {@code BoxLayout.X_AXIS, BoxLayout.Y_AXIS,
 173      *              BoxLayout.LINE_AXIS} or {@code BoxLayout.PAGE_AXIS}
 174      *
 175      * @exception AWTError  if the value of {@code axis} is invalid
 176      */
 177     @ConstructorProperties({"target", "axis"})
 178     public BoxLayout(Container target, int axis) {
 179         if (axis != X_AXIS && axis != Y_AXIS &&
 180             axis != LINE_AXIS && axis != PAGE_AXIS) {
 181             throw new AWTError("Invalid axis");
 182         }
 183         this.axis = axis;
 184         this.target = target;
 185     }
 186 
 187     /**
 188      * Constructs a BoxLayout that
 189      * produces debugging messages.
 190      *
 191      * @param target  the container that needs to be laid out
 192      * @param axis  the axis to lay out components along. Can be one of:
 193      *              {@code BoxLayout.X_AXIS, BoxLayout.Y_AXIS,
 194      *              BoxLayout.LINE_AXIS} or {@code BoxLayout.PAGE_AXIS}
 195      *
 196      * @param dbg  the stream to which debugging messages should be sent,
 197      *   null if none
 198      */
 199     BoxLayout(Container target, int axis, PrintStream dbg) {
 200         this(target, axis);
 201         this.dbg = dbg;
 202     }
 203 
 204     /**
 205      * Returns the container that uses this layout manager.
 206      *
 207      * @return the container that uses this layout manager
 208      *
 209      * @since 1.6
 210      */
 211     public final Container getTarget() {
 212         return this.target;
 213     }
 214 
 215     /**
 216      * Returns the axis that was used to lay out components.
 217      * Returns one of:
 218      * {@code BoxLayout.X_AXIS, BoxLayout.Y_AXIS,
 219      * BoxLayout.LINE_AXIS} or {@code BoxLayout.PAGE_AXIS}
 220      *
 221      * @return the axis that was used to lay out components
 222      *
 223      * @since 1.6
 224      */
 225     public final int getAxis() {
 226         return this.axis;
 227     }
 228 
 229     /**
 230      * Indicates that a child has changed its layout related information,
 231      * and thus any cached calculations should be flushed.
 232      * <p>
 233      * This method is called by AWT when the invalidate method is called
 234      * on the Container.  Since the invalidate method may be called
 235      * asynchronously to the event thread, this method may be called
 236      * asynchronously.
 237      *
 238      * @param target  the affected container
 239      *
 240      * @exception AWTError  if the target isn't the container specified to the
 241      *                      BoxLayout constructor
 242      */
 243     public synchronized void invalidateLayout(Container target) {
 244         checkContainer(target);
 245         xChildren = null;
 246         yChildren = null;
 247         xTotal = null;
 248         yTotal = null;
 249     }
 250 
 251     /**
 252      * Not used by this class.
 253      *
 254      * @param name the name of the component
 255      * @param comp the component
 256      */
 257     public void addLayoutComponent(String name, Component comp) {
 258         invalidateLayout(comp.getParent());
 259     }
 260 
 261     /**
 262      * Not used by this class.
 263      *
 264      * @param comp the component
 265      */
 266     public void removeLayoutComponent(Component comp) {
 267         invalidateLayout(comp.getParent());
 268     }
 269 
 270     /**
 271      * Not used by this class.
 272      *
 273      * @param comp the component
 274      * @param constraints constraints
 275      */
 276     public void addLayoutComponent(Component comp, Object constraints) {
 277         invalidateLayout(comp.getParent());
 278     }
 279 
 280     /**
 281      * Returns the preferred dimensions for this layout, given the components
 282      * in the specified target container.
 283      *
 284      * @param target  the container that needs to be laid out
 285      * @return the dimensions &gt;= 0 &amp;&amp; &lt;= Integer.MAX_VALUE
 286      * @exception AWTError  if the target isn't the container specified to the
 287      *                      BoxLayout constructor
 288      * @see Container
 289      * @see #minimumLayoutSize
 290      * @see #maximumLayoutSize
 291      */
 292     public Dimension preferredLayoutSize(Container target) {
 293         Dimension size;
 294         synchronized(this) {
 295             checkContainer(target);
 296             checkRequests();
 297             size = new Dimension(xTotal.preferred, yTotal.preferred);
 298         }
 299 
 300         Insets insets = target.getInsets();
 301         size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);
 302         size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);
 303         return size;
 304     }
 305 
 306     /**
 307      * Returns the minimum dimensions needed to lay out the components
 308      * contained in the specified target container.
 309      *
 310      * @param target  the container that needs to be laid out
 311      * @return the dimensions &gt;= 0 &amp;&amp; &lt;= Integer.MAX_VALUE
 312      * @exception AWTError  if the target isn't the container specified to the
 313      *                      BoxLayout constructor
 314      * @see #preferredLayoutSize
 315      * @see #maximumLayoutSize
 316      */
 317     public Dimension minimumLayoutSize(Container target) {
 318         Dimension size;
 319         synchronized(this) {
 320             checkContainer(target);
 321             checkRequests();
 322             size = new Dimension(xTotal.minimum, yTotal.minimum);
 323         }
 324 
 325         Insets insets = target.getInsets();
 326         size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);
 327         size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);
 328         return size;
 329     }
 330 
 331     /**
 332      * Returns the maximum dimensions the target container can use
 333      * to lay out the components it contains.
 334      *
 335      * @param target  the container that needs to be laid out
 336      * @return the dimensions &gt;= 0 &amp;&amp; &lt;= Integer.MAX_VALUE
 337      * @exception AWTError  if the target isn't the container specified to the
 338      *                      BoxLayout constructor
 339      * @see #preferredLayoutSize
 340      * @see #minimumLayoutSize
 341      */
 342     public Dimension maximumLayoutSize(Container target) {
 343         Dimension size;
 344         synchronized(this) {
 345             checkContainer(target);
 346             checkRequests();
 347             size = new Dimension(xTotal.maximum, yTotal.maximum);
 348         }
 349 
 350         Insets insets = target.getInsets();
 351         size.width = (int) Math.min((long) size.width + (long) insets.left + (long) insets.right, Integer.MAX_VALUE);
 352         size.height = (int) Math.min((long) size.height + (long) insets.top + (long) insets.bottom, Integer.MAX_VALUE);
 353         return size;
 354     }
 355 
 356     /**
 357      * Returns the alignment along the X axis for the container.
 358      * If the box is horizontal, the default
 359      * alignment will be returned. Otherwise, the alignment needed
 360      * to place the children along the X axis will be returned.
 361      *
 362      * @param target  the container
 363      * @return the alignment &gt;= 0.0f &amp;&amp; &lt;= 1.0f
 364      * @exception AWTError  if the target isn't the container specified to the
 365      *                      BoxLayout constructor
 366      */
 367     public synchronized float getLayoutAlignmentX(Container target) {
 368         checkContainer(target);
 369         checkRequests();
 370         return xTotal.alignment;
 371     }
 372 
 373     /**
 374      * Returns the alignment along the Y axis for the container.
 375      * If the box is vertical, the default
 376      * alignment will be returned. Otherwise, the alignment needed
 377      * to place the children along the Y axis will be returned.
 378      *
 379      * @param target  the container
 380      * @return the alignment &gt;= 0.0f &amp;&amp; &lt;= 1.0f
 381      * @exception AWTError  if the target isn't the container specified to the
 382      *                      BoxLayout constructor
 383      */
 384     public synchronized float getLayoutAlignmentY(Container target) {
 385         checkContainer(target);
 386         checkRequests();
 387         return yTotal.alignment;
 388     }
 389 
 390     /**
 391      * Called by the AWT <!-- XXX CHECK! --> when the specified container
 392      * needs to be laid out.
 393      *
 394      * @param target  the container to lay out
 395      *
 396      * @exception AWTError  if the target isn't the container specified to the
 397      *                      BoxLayout constructor
 398      */
 399     public void layoutContainer(Container target) {
 400         checkContainer(target);
 401         int nChildren = target.getComponentCount();
 402         int[] xOffsets = new int[nChildren];
 403         int[] xSpans = new int[nChildren];
 404         int[] yOffsets = new int[nChildren];
 405         int[] ySpans = new int[nChildren];
 406 
 407         Dimension alloc = target.getSize();
 408         Insets in = target.getInsets();
 409         alloc.width -= in.left + in.right;
 410         alloc.height -= in.top + in.bottom;
 411 
 412         // Resolve axis to an absolute value (either X_AXIS or Y_AXIS)
 413         ComponentOrientation o = target.getComponentOrientation();
 414         int absoluteAxis = resolveAxis( axis, o );
 415         boolean ltr = (absoluteAxis != axis) ? o.isLeftToRight() : true;
 416 
 417 
 418         // determine the child placements
 419         synchronized(this) {
 420             checkRequests();
 421 
 422             if (absoluteAxis == X_AXIS) {
 423                 SizeRequirements.calculateTiledPositions(alloc.width, xTotal,
 424                                                          xChildren, xOffsets,
 425                                                          xSpans, ltr);
 426                 SizeRequirements.calculateAlignedPositions(alloc.height, yTotal,
 427                                                            yChildren, yOffsets,
 428                                                            ySpans);
 429             } else {
 430                 SizeRequirements.calculateAlignedPositions(alloc.width, xTotal,
 431                                                            xChildren, xOffsets,
 432                                                            xSpans, ltr);
 433                 SizeRequirements.calculateTiledPositions(alloc.height, yTotal,
 434                                                          yChildren, yOffsets,
 435                                                          ySpans);
 436             }
 437         }
 438 
 439         // flush changes to the container
 440         for (int i = 0; i < nChildren; i++) {
 441             Component c = target.getComponent(i);
 442             c.setBounds((int) Math.min((long) in.left + (long) xOffsets[i], Integer.MAX_VALUE),
 443                         (int) Math.min((long) in.top + (long) yOffsets[i], Integer.MAX_VALUE),
 444                         xSpans[i], ySpans[i]);
 445 
 446         }
 447         if (dbg != null) {
 448             for (int i = 0; i < nChildren; i++) {
 449                 Component c = target.getComponent(i);
 450                 dbg.println(c.toString());
 451                 dbg.println("X: " + xChildren[i]);
 452                 dbg.println("Y: " + yChildren[i]);
 453             }
 454         }
 455 
 456     }
 457 
 458     void checkContainer(Container target) {
 459         if (this.target != target) {
 460             throw new AWTError("BoxLayout can't be shared");
 461         }
 462     }
 463 
 464     void checkRequests() {
 465         if (xChildren == null || yChildren == null) {
 466             // The requests have been invalidated... recalculate
 467             // the request information.
 468             int n = target.getComponentCount();
 469             xChildren = new SizeRequirements[n];
 470             yChildren = new SizeRequirements[n];
 471             for (int i = 0; i < n; i++) {
 472                 Component c = target.getComponent(i);
 473                 if (!c.isVisible()) {
 474                     xChildren[i] = new SizeRequirements(0,0,0, c.getAlignmentX());
 475                     yChildren[i] = new SizeRequirements(0,0,0, c.getAlignmentY());
 476                     continue;
 477                 }
 478                 Dimension min = c.getMinimumSize();
 479                 Dimension typ = c.getPreferredSize();
 480                 Dimension max = c.getMaximumSize();
 481                 xChildren[i] = new SizeRequirements(min.width, typ.width,
 482                                                     max.width,
 483                                                     c.getAlignmentX());
 484                 yChildren[i] = new SizeRequirements(min.height, typ.height,
 485                                                     max.height,
 486                                                     c.getAlignmentY());
 487             }
 488 
 489             // Resolve axis to an absolute value (either X_AXIS or Y_AXIS)
 490             int absoluteAxis = resolveAxis(axis,target.getComponentOrientation());
 491 
 492             if (absoluteAxis == X_AXIS) {
 493                 xTotal = SizeRequirements.getTiledSizeRequirements(xChildren);
 494                 yTotal = SizeRequirements.getAlignedSizeRequirements(yChildren);
 495             } else {
 496                 xTotal = SizeRequirements.getAlignedSizeRequirements(xChildren);
 497                 yTotal = SizeRequirements.getTiledSizeRequirements(yChildren);
 498             }
 499         }
 500     }
 501 
 502     /**
 503      * Given one of the 4 axis values, resolve it to an absolute axis.
 504      * The relative axis values, PAGE_AXIS and LINE_AXIS are converted
 505      * to their absolute couterpart given the target's ComponentOrientation
 506      * value.  The absolute axes, X_AXIS and Y_AXIS are returned unmodified.
 507      *
 508      * @param axis the axis to resolve
 509      * @param o the ComponentOrientation to resolve against
 510      * @return the resolved axis
 511      */
 512     private int resolveAxis( int axis, ComponentOrientation o ) {
 513         int absoluteAxis;
 514         if( axis == LINE_AXIS ) {
 515             absoluteAxis = o.isHorizontal() ? X_AXIS : Y_AXIS;
 516         } else if( axis == PAGE_AXIS ) {
 517             absoluteAxis = o.isHorizontal() ? Y_AXIS : X_AXIS;
 518         } else {
 519             absoluteAxis = axis;
 520         }
 521         return absoluteAxis;
 522    }
 523 
 524 
 525     private int axis;
 526     private Container target;
 527 
 528     private transient SizeRequirements[] xChildren;
 529     private transient SizeRequirements[] yChildren;
 530     private transient SizeRequirements xTotal;
 531     private transient SizeRequirements yTotal;
 532 
 533     private transient PrintStream dbg;
 534 }