Java/Swing JFC/Layout

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

A BorderLayout divides the space into five regions: North, West, South, East and Centre.

   <source lang="java">
  

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Insets; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class BorderExample {

 public static void main(String[] args) {
   JPanel panel = new JPanel(new BorderLayout());
   JPanel top = new JPanel();
   top.setBackground(Color.gray);
   top.setPreferredSize(new Dimension(250, 150));
   panel.add(top);
   panel.setBorder(new EmptyBorder(new Insets(10, 20, 30, 40)));
   JFrame f = new JFrame();
   f.add(panel);
   f.pack();
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



Absolute Layout Demo

   <source lang="java">
   

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* AbsoluteLayoutDemo.java is a 1.4 application that requires no other files.
*/

import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import javax.swing.JButton; import javax.swing.JFrame; public class AbsoluteLayoutDemo {

 public static void addComponentsToPane(Container pane) {
   pane.setLayout(null);
   JButton b1 = new JButton("one");
   JButton b2 = new JButton("two");
   JButton b3 = new JButton("three");
   pane.add(b1);
   pane.add(b2);
   pane.add(b3);
   Insets insets = pane.getInsets();
   Dimension size = b1.getPreferredSize();
   b1.setBounds(25 + insets.left, 5 + insets.top, size.width, size.height);
   size = b2.getPreferredSize();
   b2
       .setBounds(55 + insets.left, 40 + insets.top, size.width,
           size.height);
   size = b3.getPreferredSize();
   b3.setBounds(150 + insets.left, 15 + insets.top, size.width + 50,
       size.height + 20);
 }
 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("AbsoluteLayoutDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Set up the content pane.
   addComponentsToPane(frame.getContentPane());
   //Size and display the window.
   Insets insets = frame.getInsets();
   frame.setSize(300 + insets.left + insets.right, 125 + insets.top
       + insets.bottom);
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   //Schedule a job for the event-dispatching thread:
   //creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }

}



 </source>
   
  
 
  



Add buttons to all parts of a BorderLayout

   <source lang="java">
  

import java.awt.BorderLayout; import java.awt.Button; import java.awt.Frame; public class Main extends Frame {

 private Button north, south, east, west, center;
 public Main(String title) {
   super(title);
   north = new Button("North");
   south = new Button("South");
   east = new Button("East");
   west = new Button("West");
   center = new Button("Center");
   this.add(north, BorderLayout.NORTH);
   this.add(south, BorderLayout.SOUTH);
   this.add(east, BorderLayout.EAST);
   this.add(west, BorderLayout.WEST);
   this.add(center, BorderLayout.CENTER);
 }
 public static void main(String[] args) {
   Frame f = new Main("BorderLayout demo");
   f.pack();
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



A demonstration of the SpringLayout class

   <source lang="java">
   

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// CompassButtons.java //A demonstration of the SpringLayout class. This application puts //directional buttons on a panel and keeps them close to the edges of //the panel regardless of the panel"s size. // import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JViewport; import javax.swing.Spring; import javax.swing.SpringLayout; public class CompassButtons extends JFrame {

 JButton nb = new JButton("North");
 JButton sb = new JButton("South");
 JButton eb = new JButton("East");
 JButton wb = new JButton("West");
 JViewport viewport = new JViewport();
 public CompassButtons(String terrain) {
   super("SpringLayout Compass Demo");
   setSize(500, 300);
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   SpringLayout sl = new SpringLayout();
   Container c = getContentPane();
   c.setLayout(sl);
   int offset = 50; // gap between buttons and outside edge
   int w = 80; // width of buttons
   int h = 26; // height of buttons
   int border = 3; // border around viewport
   Spring offsetS = Spring.constant(offset);
   Spring borderS = Spring.constant(border);
   Spring widthS = Spring.constant(w);
   Spring halfWidthS = FractionSpring.half(widthS);
   Spring heightS = Spring.constant(h);
   Spring halfHeightS = FractionSpring.half(heightS);
   Spring leftEdgeS = sl.getConstraint(SpringLayout.WEST, c);
   Spring topEdgeS = sl.getConstraint(SpringLayout.NORTH, c);
   Spring rightEdgeS = sl.getConstraint(SpringLayout.EAST, c);
   Spring bottomEdgeS = sl.getConstraint(SpringLayout.SOUTH, c);
   Spring xCenterS = FractionSpring.half(rightEdgeS);
   Spring yCenterS = FractionSpring.half(bottomEdgeS);
   Spring leftBorder = Spring.sum(leftEdgeS, borderS);
   Spring topBorder = Spring.sum(topEdgeS, borderS);
   Spring northX = Spring.sum(xCenterS, Spring.minus(halfWidthS));
   Spring southY = Spring.sum(bottomEdgeS, Spring.minus(Spring.sum(
       heightS, offsetS)));
   Spring eastX = Spring.sum(rightEdgeS, Spring.minus(Spring.sum(widthS,
       offsetS)));
   Spring eastY = Spring.sum(yCenterS, Spring.minus(halfHeightS));
   c.add(nb,
       new SpringLayout.Constraints(northX, offsetS, widthS, heightS));
   c
       .add(sb, new SpringLayout.Constraints(northX, southY, widthS,
           heightS));
   c.add(wb);
   sl.getConstraints(wb).setX(offsetS);
   sl.getConstraints(wb).setY(eastY);
   sl.getConstraints(wb).setWidth(widthS);
   sl.getConstraints(wb).setHeight(heightS);
   c.add(eb);
   sl.getConstraints(eb).setX(eastX);
   sl.getConstraints(eb).setY(eastY);
   sl.getConstraints(eb).setWidth(widthS);
   sl.getConstraints(eb).setHeight(heightS);
   c.add(viewport); // this sets a bounds of (0,0,pref_width,pref_height)
   // The order here is important...need to have a valid width and height
   // in place before binding the (x,y) location
   sl.putConstraint(SpringLayout.SOUTH, viewport, Spring.minus(borderS),
       SpringLayout.SOUTH, c);
   sl.putConstraint(SpringLayout.EAST, viewport, Spring.minus(borderS),
       SpringLayout.EAST, c);
   sl.putConstraint(SpringLayout.NORTH, viewport, topBorder,
       SpringLayout.NORTH, c);
   sl.putConstraint(SpringLayout.WEST, viewport, leftBorder,
       SpringLayout.WEST, c);
   ImageIcon icon = new ImageIcon(getClass().getResource(terrain));
   viewport.setView(new JLabel(icon));
   // Hook up the buttons. See the CompassScroller class (on-line) for
   // details
   // on controlling the viewport.
   nb.setActionCommand(CompassScroller.NORTH);
   sb.setActionCommand(CompassScroller.SOUTH);
   wb.setActionCommand(CompassScroller.WEST);
   eb.setActionCommand(CompassScroller.EAST);
   CompassScroller scroller = new CompassScroller(viewport);
   nb.addActionListener(scroller);
   sb.addActionListener(scroller);
   eb.addActionListener(scroller);
   wb.addActionListener(scroller);
   setVisible(true);
 }
 public static void main(String args[]) {
   new CompassButtons(args.length == 1 ? args[0] : "terrain.gif");
 }

} //FractionSpring.java //A Spring extension that calculates its values based on an anchor Spring //and a multiplier (> 0.0). Note that values greater than 1.0 can be //used. // class FractionSpring extends Spring {

 protected Spring parent;
 protected double fraction;
 public FractionSpring(Spring p, double f) {
   if (p == null) {
     throw new NullPointerException("Parent spring cannot be null");
   }
   parent = p;
   fraction = f;
 }
 public int getValue() {
   return (int) Math.round(parent.getValue() * fraction);
 }
 public int getPreferredValue() {
   return (int) Math.round(parent.getPreferredValue() * fraction);
 }
 public int getMinimumValue() {
   return (int) Math.round(parent.getMinimumValue() * fraction);
 }
 public int getMaximumValue() {
   return (int) Math.round(parent.getMaximumValue() * fraction);
 }
 public void setValue(int val) {
   // Uncomment this next line to watch when our spring is resized:
   // System.err.println("Value to setValue: " + val);
   if (val == UNSET) {
     return;
   }
   throw new UnsupportedOperationException(
       "Cannot set value on a derived spring");
 }
 public static FractionSpring half(Spring s) {
   return new FractionSpring(s, 0.5);
 }

} //CompassScroller.java //A simple ActionListener that can move the view of a viewport //north, south, east and west by specified units. // class CompassScroller implements ActionListener {

 public static final String NORTH = "North";
 public static final String SOUTH = "South";
 public static final String EAST = "East";
 public static final String WEST = "West";
 private JViewport viewport;
 private Point p;
 public CompassScroller(JViewport viewport) {
   this.viewport = viewport;
   p = new Point();
 }
 public void actionPerformed(ActionEvent ae) {
   Dimension dv = viewport.getViewSize();
   Dimension de = viewport.getExtentSize();
   String command = ae.getActionCommand();
   if (command == NORTH) {
     if (p.y > 9) {
       p.y -= 10;
     }
   } else if (command == SOUTH) {
     if (p.y + de.height < dv.height) {
       p.y += 10;
     }
   } else if (command == EAST) {
     if (p.x + de.width < dv.width) {
       p.x += 10;
     }
   } else if (command == WEST) {
     if (p.x > 9) {
       p.x -= 10;
     }
   }
   viewport.setViewPosition(p);
 }

}



 </source>
   
  
 
  



A horizontal layout layout manager that allocates horizontal space in specified proportions

   <source lang="java">
    

package com.equitysoft.cellspark; /** THIS PROGRAM IS PROVIDED "AS IS" WITHOUT ANY WARRANTIES (OR CONDITIONS), EXPRESS OR IMPLIED WITH RESPECT TO THE PROGRAM, INCLUDING THE IMPLIED WARRANTIES (OR CONDITIONS) OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK ARISING OUT OF USE OR PERFORMANCE OF THE PROGRAM AND DOCUMENTATION REMAINS WITH THE USER.

  • /

import java.awt.*; import java.util.*; /**

*
* A horizontal layout layout manager that allocates horizontal space in specified proportions.
* The same can be done with GridBagLayout but GridBagLayout has a problem when space is resized
* particularly when moving a JSplitPane divider - the proportions will suddenly change
* for no apparent reason. ProportionalLayout solves the problem.
*
* Revision date 12th July 2001
*
* @author Colin Mummery  e-mail: colin_mummery@yahoo.ru Homepage:www.kagi.ru/equitysoft
*/

public class ProportionalLayout implements LayoutManager{

 private Hashtable comps;
 private int[] proportions;
 private int total; //The total of the proportions
 private int num; //The number in the array

//Constructors /**

  • Constructs a ProportinalLayout instance with the specified horizontal component proportions
  • @param proportions An int array of values indicating horizontal proportions. An array of 2,1,1 would
  • give the first component added half the space horizontally, the second and the third would each get a quarter.
  • More components would not be given any space at all. When there are less than the expected number of components
  • the unused values in the proportions array will correspond to blank space in the layout.
  • /
  public ProportionalLayout(int[] proportions){
 this.proportions=proportions;
 num=proportions.length;
 for(int i=0;i<num;i++){
   int prop=proportions[i];
   total+=prop;
 }
  }

//----------------------------------------------------------------------------

  private Dimension layoutSize(Container parent,boolean minimum){
 Dimension dim=new Dimension(0,0);
 synchronized(parent.getTreeLock()){
   int n=parent.getComponentCount();
   int cnt=0;
   for(int i=0;i<n;i++){
     Component c=parent.getComponent(i); int maxhgt=0;
     if(c.isVisible()){
       Dimension d=(minimum)? c.getMinimumSize() : c.getPreferredSize();
       dim.width+=d.width;
       if(d.height>dim.height)dim.height=d.height;
     }
     cnt++; if(cnt==num)break;
   }
 }
 Insets insets=parent.getInsets();
 dim.width+=insets.left+insets.right;
 dim.height+=insets.top+insets.bottom;
 return dim;
  }

//----------------------------------------------------------------------------- /**

* Lays out the container.
*/
  public void layoutContainer(Container parent){
 Insets insets=parent.getInsets();
 synchronized(parent.getTreeLock()){
   int n=parent.getComponentCount();
   Dimension pd=parent.getSize();

//do layout

   int cnt=0;
   int totalwid=pd.width-insets.left-insets.right;
   int x=insets.left; int cumwid=0;
   for(int i=0;i<n;i++){
     Component c=parent.getComponent(i);
     int wid=proportions[i]*totalwid/total;
     c.setBounds(x,insets.top,wid,pd.height-insets.bottom-insets.top);
     x+=wid;
     cnt++; if(cnt==num)break;
   }
 }
  }

//-----------------------------------------------------------------------------

  public Dimension minimumLayoutSize(Container parent){return layoutSize(parent,false);}

//-----------------------------------------------------------------------------

  public Dimension preferredLayoutSize(Container parent){return layoutSize(parent,false);}

//---------------------------------------------------------------------------- /**

* Not used by this class
*/
  public void addLayoutComponent(String name,Component comp){}

//----------------------------------------------------------------------------- /**

* Not used by this class
*/
  public void removeLayoutComponent(Component comp){}

//-----------------------------------------------------------------------------

  public String toString(){
 StringBuffer sb=new StringBuffer();
 sb.append(getClass().getName()).append("["); int len=proportions.length;
 for(int i=0;i<len;i++){
   sb.append("p").append(i).append("=").append(proportions[i]);
   if(i!=len-1)sb.append(",");
 }
 sb.append("]");
 return sb.toString();
  }

//----------------------------------------------------------------------------- }



 </source>
   
  
 
  



A JTextField for displaying insets.

   <source lang="java">
 

/*

* JCommon : a free general purpose class library for the Java(tm) platform
* 
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info:  http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* --------------------
* InsetsTextField.java
* --------------------
* (C) Copyright 2000-2008, by Andrzej Porebski.
*
* Original Author:  Andrzej Porebski;
* Contributor(s):   Arnaud Lelievre;
*
* $Id: InsetsTextField.java,v 1.4 2008/12/18 09:57:32 mungady Exp $
*
* Changes (from 7-Nov-2001)
* -------------------------
* 07-Nov-2001 : Added to com.jrefinery.ui package (DG);
* 08-Sep-2003 : Added internationalization via use of properties
*               resourceBundle (RFE 690236) (AL);
* 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by
*               Jess Thrysoee (DG);
*
*/

import java.awt.Insets; import java.util.ResourceBundle; import javax.swing.JTextField;

/**

* A JTextField for displaying insets.
*
* @author Andrzej Porebski
*/

public class InsetsTextField extends JTextField {

   /**
    * Default constructor. Initializes this text field with formatted string
    * describing provided insets.
    *
    * @param insets  the insets.
    */
   public InsetsTextField(final Insets insets) {
       super();
       setInsets(insets);
       setEnabled(false);
   }
   /**
    * Returns a formatted string describing provided insets.
    *
    * @param insets  the insets.
    *
    * @return the string.
    */
   public String formatInsetsString(Insets insets) {
       insets = (insets == null) ? new Insets(0, 0, 0, 0) : insets;
       return
           "T" + insets.top + ", "
            + "L" + insets.left + ", "
            + "B" + insets.bottom + ", "
            + "R" + insets.right;
   }
   /**
    * Sets the text of this text field to the formatted string
    * describing provided insets. If insets is null, empty insets
    * (0,0,0,0) are used.
    *
    * @param insets  the insets.
    */
   public void setInsets(final Insets insets) {
       setText(formatInsetsString(insets));
   }

}


 </source>
   
  
 
  



A test of the BoxLayout manager using the Box utility class

   <source lang="java">
   

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// HBox.java //A quick test of the BoxLayout manager using the Box utility class. // import java.awt.Button; import java.awt.Panel; import javax.swing.BoxLayout; import javax.swing.JFrame; public class HBox extends JFrame {

 public HBox() {
   super("Horizontal Box Test Frame");
   setSize(200, 100);
   Panel box = new Panel();
   // Use BoxLayout.Y_AXIS below if you want a vertical box
   box.setLayout(new BoxLayout(box, BoxLayout.X_AXIS));
   setContentPane(box);
   for (int i = 0; i < 3; i++) {
     Button b = new Button("B" + i);
     box.add(b);
   }
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   setVisible(true);
 }
 public static void main(String args[]) {
   HBox bt = new HBox();
 }

}



 </source>
   
  
 
  



A test of the box layout manager using the Box utility class 2

   <source lang="java">
   

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// HBoxWithGlue.java //A quick test of the box layout manager using the Box utility class. // import java.awt.Button; import javax.swing.Box; import javax.swing.JFrame; public class HBoxWithGlue extends JFrame {

 public HBoxWithGlue() {
   super("Box & Glue Frame");
   setSize(350, 100);
   Box box = Box.createHorizontalBox();
   setContentPane(box);
   box.add(Box.createHorizontalGlue());
   for (int i = 0; i < 3; i++) {
     Button b = new Button("B" + i);
     box.add(b);
   }
   box.add(Box.createHorizontalGlue());
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   setVisible(true);
 }
 public static void main(String args[]) {
   HBoxWithGlue bt = new HBoxWithGlue();
 }

}



 </source>
   
  
 
  



A test of the BoxLayout manager using the Box utility class 3

   <source lang="java">
   

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// VBox.java //A quick test of the BoxLayout manager using the Box utility class. //This box is laid out vertically. // import java.awt.Button; import java.awt.Panel; import javax.swing.BoxLayout; import javax.swing.JFrame; public class VBox extends JFrame {

 public VBox() {
   super("Vertical Box Test Frame");
   setSize(200, 100);
   Panel box = new Panel();
   // Use BoxLayout.X_AXIS below if you want a horizontal box
   box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
   setContentPane(box);
   for (int i = 0; i < 3; i++) {
     Button b = new Button("B" + i);
     box.add(b);
   }
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   setVisible(true);
 }
 public static void main(String args[]) {
   VBox bt = new VBox();
 }

}



 </source>
   
  
 
  



A test of the OverlayLayout manager allowing experimentation

   <source lang="java">
   

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

//OverlayTest.java //A test of the OverlayLayout manager allowing experimentation. // import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.OverlayLayout; public class OverlayTest extends JFrame {

public OverlayTest() {
    super("OverlayLayout Test");
    setSize(500, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    final Container c = getContentPane();
    c.setLayout(new GridBagLayout());
    final JPanel p1 = new GridPanel();
    final OverlayLayout overlay = new OverlayLayout(p1);
    p1.setLayout(overlay);
    final JButton jb1 = new JButton("B1");
    final JButton jb2 = new JButton("B2");
    final JButton jb3 = new JButton("B3");
    Dimension b1 = new Dimension(60, 50);
    Dimension b2 = new Dimension(80, 40);
    Dimension b3 = new Dimension(100, 60);
    jb1.setMinimumSize(b1);
    jb1.setMaximumSize(b1);
    jb1.setPreferredSize(b1);
    jb2.setMinimumSize(b2);
    jb2.setMaximumSize(b2);
    jb2.setPreferredSize(b2);
    jb3.setMinimumSize(b3);
    jb3.setMaximumSize(b3);
    jb3.setPreferredSize(b3);
    SimpleReporter reporter = new SimpleReporter();
    jb1.addActionListener(reporter);
    jb2.addActionListener(reporter);
    jb3.addActionListener(reporter);
    p1.add(jb1);
    p1.add(jb2);
    p1.add(jb3);
    JPanel p2 = new JPanel();
    p2.setLayout(new GridLayout(2,6));
    p2.add(new JLabel("B1 X", JLabel.CENTER));
    p2.add(new JLabel("B1 Y", JLabel.CENTER));
    p2.add(new JLabel("B2 X", JLabel.CENTER));
    p2.add(new JLabel("B2 Y", JLabel.CENTER));
    p2.add(new JLabel("B3 X", JLabel.CENTER));
    p2.add(new JLabel("B3 Y", JLabel.CENTER));
    p2.add(new JLabel(""));
    final JTextField x1 = new JTextField("0.0", 4); // Button1 x alignment
    final JTextField y1 = new JTextField("0.0", 4); // Button1 y alignment
    final JTextField x2 = new JTextField("0.0", 4); 
    final JTextField y2 = new JTextField("0.0", 4); 
    final JTextField x3 = new JTextField("0.0", 4); 
    final JTextField y3 = new JTextField("0.0", 4); 
    p2.add(x1);
    p2.add(y1);
    p2.add(x2);
    p2.add(y2);
    p2.add(x3);
    p2.add(y3);
    GridBagConstraints constraints = new GridBagConstraints();
    c.add(p1, constraints);
    constraints.gridx = 1;
    JButton updateButton = new JButton("Update");
    updateButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            jb1.setAlignmentX(
                Float.valueOf(x1.getText().trim()).floatValue());
            jb1.setAlignmentY(
                Float.valueOf(y1.getText().trim()).floatValue());
            jb2.setAlignmentX(
                Float.valueOf(x2.getText().trim()).floatValue());
            jb2.setAlignmentY(
                Float.valueOf(y2.getText().trim()).floatValue());
            jb3.setAlignmentX(
                Float.valueOf(x3.getText().trim()).floatValue());
            jb3.setAlignmentY(
                Float.valueOf(y3.getText().trim()).floatValue());
            p1.revalidate();
        }
    });
    c.add(updateButton, constraints);
    constraints.gridx = 0;
    constraints.gridy = 1;
    constraints.gridwidth = 2;
    c.add(p2, constraints);
}
public static void main(String args[]) {
    OverlayTest ot = new OverlayTest();
    ot.setVisible(true);
}
public class SimpleReporter implements ActionListener {
    public void actionPerformed(ActionEvent ae) {
        System.out.println(ae.getActionCommand());
    }
}
public class GridPanel extends JPanel {
    public void paint(Graphics g) {
        super.paint(g);
        int w = getSize().width;
        int h = getSize().height;
        g.setColor(Color.red);
        g.drawRect(0,0,w-1,h-1);
        g.drawLine(w/2,0,w/2,h);
        g.drawLine(0,h/2,w,h/2);
    }
}

}




 </source>
   
  
 
  



A typical usage of a border layout manager.

   <source lang="java">
  

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Insets; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JTextArea; import javax.swing.JToolBar; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; public class BorderLayoutExample {

 public static void main(String[] args) {
   JFrame f = new JFrame();
   JMenuBar menubar = new JMenuBar();
   JMenu file = new JMenu("File");
   menubar.add(file);
   f.setJMenuBar(menubar);
   JToolBar toolbar = new JToolBar();
   toolbar.setFloatable(false);
   JButton bexit = new JButton(new ImageIcon("exit.png"));
   bexit.setBorder(new EmptyBorder(0, 0, 0, 0));
   toolbar.add(bexit);
   f.add(toolbar, BorderLayout.NORTH);
   JToolBar vertical = new JToolBar(JToolBar.VERTICAL);
   vertical.setFloatable(false);
   vertical.setMargin(new Insets(10, 5, 5, 5));
   JButton selectb = new JButton(new ImageIcon("a.png"));
   selectb.setBorder(new EmptyBorder(3, 0, 3, 0));
   JButton freehandb = new JButton(new ImageIcon("b.png"));
   freehandb.setBorder(new EmptyBorder(3, 0, 3, 0));
   JButton shapeedb = new JButton(new ImageIcon("c.png"));
   shapeedb.setBorder(new EmptyBorder(3, 0, 3, 0));
   vertical.add(selectb);
   vertical.add(freehandb);
   vertical.add(shapeedb);
   f.add(vertical, BorderLayout.WEST);
   f.add(new JTextArea(), BorderLayout.CENTER);
   JLabel statusbar = new JLabel(" Statusbar");
   statusbar.setPreferredSize(new Dimension(-1, 22));
   statusbar.setBorder(LineBorder.createGrayLineBorder());
   f.add(statusbar, BorderLayout.SOUTH);
   f.setSize(350, 300);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



A vertical layout manager similar to java.awt.FlowLayout

   <source lang="java">
    

/** THIS PROGRAM IS PROVIDED "AS IS" WITHOUT ANY WARRANTIES (OR CONDITIONS), EXPRESS OR IMPLIED WITH RESPECT TO THE PROGRAM, INCLUDING THE IMPLIED WARRANTIES (OR CONDITIONS) OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK ARISING OUT OF USE OR PERFORMANCE OF THE PROGRAM AND DOCUMENTATION REMAINS WITH THE USER.

  • /

import java.awt.*; import java.util.*; /**

*
* A vertical layout manager similar to java.awt.FlowLayout.
* Like FlowLayout components do not expand to fill available space except when the horizontal alignment
* is BOTH
* in which case components are stretched horizontally. Unlike FlowLayout, components will not wrap to form another
* column if there isn"t enough space vertically. VerticalLayout can optionally anchor components to the top or bottom
* of the display area or center them between the top and bottom.
*
* Revision date 12th July 2001
*
* @author Colin Mummery  e-mail: colin_mummery@yahoo.ru Homepage:www.kagi.ru/equitysoft -
* Based on "FlexLayout" in Java class libraries Vol 2 Chan/Lee Addison-Wesley 1998
*/

public class VerticalLayout implements LayoutManager{ /**

  • The horizontal alignment constant that designates centering. Also used to designate center anchoring.
  • /
 public final static int CENTER=0;

/**

  • The horizontal alignment constant that designates right justification.
  • /
 public final static int RIGHT=1;

/**

  • The horizontal alignment constant that designates left justification.
  • /
 public final static int LEFT=2;

/**

  • The horizontal alignment constant that designates stretching the component horizontally.
  • /
 public final static int BOTH=3;

/**

  • The anchoring constant that designates anchoring to the top of the display area
  • /
 public final static int TOP=1;

/**

  • The anchoring constant that designates anchoring to the bottom of the display area
  • /
 public final static int BOTTOM=2;
 private int vgap; //the vertical vgap between components...defaults to 5
 private int alignment; //LEFT, RIGHT, CENTER or BOTH...how the components are justified
 private int anchor; //TOP, BOTTOM or CENTER ...where are the components positioned in an overlarge space
 private Hashtable comps;

//Constructors /**

  • Constructs an instance of VerticalLayout with a vertical vgap of 5 pixels, horizontal centering and anchored to
  • the top of the display area.
  • /
  public VerticalLayout(){
 this(5,CENTER,TOP);
  }

/**

  • Constructs a VerticalLayout instance with horizontal centering, anchored to the top with the specified vgap
  • @param vgap An int value indicating the vertical seperation of the components
  • /
  public VerticalLayout(int vgap){
 this(vgap,CENTER,TOP);
  }

/**

  • Constructs a VerticalLayout instance anchored to the top with the specified vgap and horizontal alignment
  • @param vgap An int value indicating the vertical seperation of the components
  • @param alignment An int value which is one of RIGHT, LEFT, CENTER, BOTH for the horizontal alignment.
  • /
  public VerticalLayout(int vgap,int alignment){
 this(vgap,alignment,TOP);
  }

/**

  • Constructs a VerticalLayout instance with the specified vgap, horizontal alignment and anchoring
  • @param vgap An int value indicating the vertical seperation of the components
  • @param alignment An int value which is one of RIGHT, LEFT, CENTER, BOTH for the horizontal alignment.
  • @param anchor An int value which is one of TOP, BOTTOM, CENTER indicating where the components are
  • to appear if the display area exceeds the minimum necessary.
  • /
  public VerticalLayout(int vgap,int alignment,int anchor){
 this.vgap=vgap; this.alignment=alignment; this.anchor=anchor;
  }

//----------------------------------------------------------------------------

  private Dimension layoutSize(Container parent,boolean minimum){
 Dimension dim=new Dimension(0,0);
 Dimension d;
 synchronized(parent.getTreeLock()){
   int n=parent.getComponentCount();
   for(int i=0;i<n;i++){
     Component c=parent.getComponent(i);
     if(c.isVisible()){
       d=minimum ? c.getMinimumSize() : c.getPreferredSize();
       dim.width=Math.max(dim.width,d.width); dim.height+=d.height;
       if(i>0)dim.height+=vgap;
     }
   }
 }
 Insets insets=parent.getInsets();
 dim.width+=insets.left+insets.right;
 dim.height+=insets.top+insets.bottom+vgap+vgap;
 return dim;
  }

//----------------------------------------------------------------------------- /**

* Lays out the container.
*/
  public void layoutContainer(Container parent){
 Insets insets=parent.getInsets();
 synchronized(parent.getTreeLock()){
   int n=parent.getComponentCount();
   Dimension pd=parent.getSize(); int y=0;

//work out the total size

   for(int i=0;i<n;i++){
     Component c=parent.getComponent(i);
     Dimension d=c.getPreferredSize();
     y+=d.height+vgap;
   }
   y-=vgap; //otherwise there"s a vgap too many

//Work out the anchor paint

   if(anchor==TOP)y=insets.top;
   else if(anchor==CENTER)y=(pd.height-y)/2;
   else y=pd.height-y-insets.bottom;

//do layout

   for(int i=0;i<n;i++){
     Component c=parent.getComponent(i);
     Dimension d=c.getPreferredSize();
     int x=insets.left; int wid=d.width;
     if(alignment==CENTER)x=(pd.width-d.width)/2;
     else if(alignment==RIGHT)x=pd.width-d.width-insets.right;
     else if(alignment==BOTH)wid=pd.width-insets.left-insets.right;
     c.setBounds(x,y,wid,d.height);
     y+=d.height+vgap;
   }
 }
  }

//-----------------------------------------------------------------------------

  public Dimension minimumLayoutSize(Container parent){return layoutSize(parent,false);}

//-----------------------------------------------------------------------------

  public Dimension preferredLayoutSize(Container parent){return layoutSize(parent,false);}

//---------------------------------------------------------------------------- /**

* Not used by this class
*/
  public void addLayoutComponent(String name,Component comp){}

//----------------------------------------------------------------------------- /**

* Not used by this class
*/
  public void removeLayoutComponent(Component comp){}

//-----------------------------------------------------------------------------

  public String toString(){return getClass().getName()+"[vgap="+vgap+" align="+alignment+" anchor="+anchor+"]";}

}



 </source>
   
  
 
  



BorderLayout Pane

   <source lang="java">
   

/*

* Copyright (c) 2000 David Flanagan. All rights reserved. This code is from the
* book Java Examples in a Nutshell, 2nd Edition. It is provided AS-IS, WITHOUT
* ANY WARRANTY either expressed or implied. You may study, use, and modify it
* for any non-commercial purpose. You may distribute it non-commercially as
* long as you retain this notice. For a commercial use license, or to purchase
* the book (recommended), visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.awt.BorderLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class BorderLayoutPane extends JPanel {

 String[] borders = { "North", "East", "South", "West", "Center" };
 public BorderLayoutPane() {
   // Use a BorderLayout with 10-pixel margins between components
   this.setLayout(new BorderLayout(10, 10));
   for (int i = 0; i < 5; i++) { // Add children to the pane
     this.add(new JButton(borders[i]), // Add this component
         borders[i]); // Using this constraint
   }
 }
 public static void main(String[] a) {
   JFrame f = new JFrame();
   f.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   f.setContentPane(new BorderLayoutPane());
   f.pack();
   f.setVisible(true);
 }

}




 </source>
   
  
 
  



Box Layout: Adding struts.

   <source lang="java">
   

// : c14:Box2.java // Adding struts. // <applet code=Box2 width=450 height=300></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.BorderLayout; import java.awt.Container; import javax.swing.Box; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; public class Box2 extends JApplet {

 public void init() {
   Box bv = Box.createVerticalBox();
   for (int i = 0; i < 5; i++) {
     bv.add(new JButton("bv " + i));
     bv.add(Box.createVerticalStrut(i * 10));
   }
   Box bh = Box.createHorizontalBox();
   for (int i = 0; i < 5; i++) {
     bh.add(new JButton("bh " + i));
     bh.add(Box.createHorizontalStrut(i * 10));
   }
   Container cp = getContentPane();
   cp.add(BorderLayout.EAST, bv);
   cp.add(BorderLayout.SOUTH, bh);
 }
 public static void main(String[] args) {
   run(new Box2(), 450, 300);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~




 </source>
   
  
 
  



BoxLayout Alignment

   <source lang="java">
   

import java.awt.BorderLayout; import java.awt.Button; import java.awt.Container; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; public class YAxisAlignXButtonMixed {

 static public class AButton extends Button {
   float alignment;
   AButton(String label, float alignment) {
     super(label);
     this.alignment = alignment;
   }
   public float getAlignmentX() {
     return alignment;
   }
 }
 private static Container makeIt(String title) {
   JPanel container = new JPanel();
   container.setBorder(BorderFactory.createTitledBorder(title));
   BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
   container.setLayout(layout);
   AButton button = new AButton("0.0", 0.0f);
   container.add(button);
   button = new AButton(".25", .25f);
   container.add(button);
   button = new AButton(".50", .50f);
   container.add(button);
   button = new AButton(".75", .75f);
   container.add(button);
   button = new AButton("1.0", 1.0f);
   container.add(button);
   return container;
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Alignment Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container panel = makeIt("AWT Button");
   Container contentPane = frame.getContentPane();
   contentPane.add(panel, BorderLayout.CENTER);
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



BoxLayout alignment 2

   <source lang="java">
   

import java.awt.BorderLayout; import java.awt.ruponent; import java.awt.Container; import java.awt.Graphics; import java.awt.Insets; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class XAxisDiffAlign {

 private static Container makeIt(String title, boolean more) {
   JPanel container = new JPanel() {
     public void paintComponent(Graphics g) {
       super.paintComponent(g);
       Insets insets = getInsets();
       int width = getWidth();
       int height = getHeight() - insets.top - insets.bottom;
       int halfHeight = height / 2 + insets.top;
       g.drawLine(0, halfHeight, width, halfHeight);
     }
   };
   container.setBorder(BorderFactory.createTitledBorder(title));
   BoxLayout layout = new BoxLayout(container, BoxLayout.X_AXIS);
   container.setLayout(layout);
   JButton button;
   button = new JButton("0.0");
   button.setOpaque(false);
   button.setAlignmentY(Component.TOP_ALIGNMENT);
   container.add(button);
   if (more) {
     button = new JButton(".25");
     button.setOpaque(false);
     button.setAlignmentY(0.25f);
     container.add(button);
     button = new JButton(".5");
     button.setOpaque(false);
     button.setAlignmentY(Component.CENTER_ALIGNMENT);
     container.add(button);
     button = new JButton(".75");
     button.setOpaque(false);
     button.setAlignmentY(0.75f);
     container.add(button);
   }
   button = new JButton("1.0");
   button.setOpaque(false);
   button.setAlignmentY(Component.BOTTOM_ALIGNMENT);
   container.add(button);
   return container;
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Alignment Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container panel1 = makeIt("Mixed", false);
   Container panel2 = makeIt("Mixed", true);
   Container contentPane = frame.getContentPane();
   contentPane.add(panel1, BorderLayout.WEST);
   contentPane.add(panel2, BorderLayout.EAST);
   frame.pack();
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



BoxLayout Component alignment

   <source lang="java">
   

import java.awt.ruponent; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class YAxisAlignX {

 private static Container makeIt(String title, float alignment) {
   String labels[] = { "--", "----", "--------", "------------" };
   JPanel container = new JPanel();
   container.setBorder(BorderFactory.createTitledBorder(title));
   BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
   container.setLayout(layout);
   for (int i = 0, n = labels.length; i < n; i++) {
     JButton button = new JButton(labels[i]);
     button.setAlignmentX(alignment);
     container.add(button);
   }
   return container;
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Alignment Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container panel1 = makeIt("Left", Component.LEFT_ALIGNMENT);
   Container panel2 = makeIt("Center", Component.CENTER_ALIGNMENT);
   Container panel3 = makeIt("Right", Component.RIGHT_ALIGNMENT);
   Container contentPane = frame.getContentPane();
   contentPane.setLayout(new FlowLayout());
   contentPane.add(panel1);
   contentPane.add(panel2);
   contentPane.add(panel3);
   frame.pack();
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



BoxLayout demo 1

   <source lang="java">
   

import java.awt.Container; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; public class BoxLayoutTest extends JFrame implements ActionListener {

 private Box horizontalBox;
 private Box verticalBox;
 private Box horizontalStrutsAndGlueBox;
 private Box verticalStrutsAndGlueBox;
 private Box currentBox;
 private JCheckBox strutsAndGlueCheckBox;
 private JRadioButton horizontalButton;
 private JRadioButton verticalButton;
 public BoxLayoutTest() {
   setTitle("BoxLayoutTest");
   setSize(300, 300);
   addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   horizontalBox = createBox(true, false);
   verticalBox = createBox(false, false);
   horizontalStrutsAndGlueBox = createBox(true, true);
   verticalStrutsAndGlueBox = createBox(false, true);
   JPanel panel = new JPanel();
   panel.setLayout(new GridLayout(3, 1, 3, 3));
   ButtonGroup directionGroup = new ButtonGroup();
   horizontalButton = addRadioButton(panel, directionGroup, "Horizontal",
       true);
   verticalButton = addRadioButton(panel, directionGroup, "Vertical",
       false);
   strutsAndGlueCheckBox = addCheckBox(panel, "Struts and Glue");
   Container contentPane = getContentPane();
   contentPane.add(panel, "South");
   contentPane.add(horizontalBox, "Center");
   currentBox = horizontalBox;
 }
 public Box createBox(boolean horizontal, boolean strutsAndGlue) {
   Box b;
   if (horizontal)
     b = Box.createHorizontalBox();
   else
     b = Box.createVerticalBox();
   b.add(new JLabel("Name: "));
   b.add(new JTextField());
   if (strutsAndGlue)
     if (horizontal)
       b.add(Box.createHorizontalStrut(5));
     else
       b.add(Box.createVerticalStrut(5));
   b.add(new JLabel("Password: "));
   b.add(new JTextField());
   if (strutsAndGlue)
     b.add(Box.createGlue());
   b.add(new JButton("Ok"));
   return b;
 }
 public JRadioButton addRadioButton(JPanel p, ButtonGroup g, String name,
     boolean selected) {
   JRadioButton button = new JRadioButton(name, selected);
   button.addActionListener(this);
   g.add(button);
   p.add(button);
   return button;
 }
 public JCheckBox addCheckBox(JPanel p, String name) {
   JCheckBox checkBox = new JCheckBox(name);
   checkBox.addActionListener(this);
   p.add(checkBox);
   return checkBox;
 }
 public void actionPerformed(ActionEvent evt) {
   Container contentPane = getContentPane();
   contentPane.remove(currentBox);
   if (horizontalButton.isSelected()) {
     if (strutsAndGlueCheckBox.isSelected()) {
       currentBox = horizontalStrutsAndGlueBox;
     } else {
       currentBox = horizontalBox;
     }
   } else {
     if (strutsAndGlueCheckBox.isSelected()) {
       currentBox = verticalStrutsAndGlueBox;
     } else {
       currentBox = verticalBox;
     }
   }
   contentPane.add(currentBox, "Center");
   contentPane.validate();
   repaint();
 }
 public static void main(String[] args) {
   JFrame f = new BoxLayoutTest();
   f.show();
 }

}



 </source>
   
  
 
  



BoxLayout Demo 3

   <source lang="java">
   

import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class StrutSample {

 public static void main(String args[]) {
   Box horizontalBox;
   JPanel panel;
   JFrame frame = new JFrame("Horizontal Strut");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container contentPane = frame.getContentPane();
   contentPane.setLayout(new GridLayout(0, 1));
   horizontalBox = Box.createHorizontalBox();
   horizontalBox.add(Box.createHorizontalStrut(10));
   horizontalBox.add(new JButton("Left"));
   horizontalBox.add(new JButton("Middle"));
   horizontalBox.add(new JButton("Right"));
   panel = new JPanel(new BorderLayout());
   panel.add(horizontalBox);
   panel.setBorder(BorderFactory.createTitledBorder("Beginning Strut"));
   contentPane.add(panel);
   horizontalBox = Box.createHorizontalBox();
   horizontalBox.add(new JButton("Left"));
   horizontalBox.add(Box.createHorizontalStrut(10));
   horizontalBox.add(new JButton("Middle"));
   horizontalBox.add(Box.createHorizontalStrut(25));
   horizontalBox.add(new JButton("Right"));
   panel = new JPanel(new BorderLayout());
   panel.add(horizontalBox);
   panel.setBorder(BorderFactory.createTitledBorder("2 Middle Struts"));
   contentPane.add(panel);
   horizontalBox = Box.createHorizontalBox();
   horizontalBox.add(Box.createHorizontalStrut(25));
   horizontalBox.add(new JButton("Left"));
   horizontalBox.add(new JButton("Middle"));
   horizontalBox.add(new JButton("Right"));
   horizontalBox.add(Box.createHorizontalStrut(10));
   panel = new JPanel(new BorderLayout());
   panel.add(horizontalBox);
   panel.setBorder(BorderFactory
       .createTitledBorder("Beginning/End Struts"));
   contentPane.add(panel);
   horizontalBox = Box.createHorizontalBox();
   horizontalBox.add(new JButton("Left"));
   horizontalBox.add(new JButton("Middle"));
   horizontalBox.add(new JButton("Right"));
   panel = new JPanel(new BorderLayout());
   horizontalBox.add(Box.createHorizontalStrut(10));
   panel.add(horizontalBox);
   panel.setBorder(BorderFactory.createTitledBorder("End Strut"));
   contentPane.add(panel);
   frame.setSize(300, 300);
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



BoxLayout Demo 4

   <source lang="java">
   

import java.awt.Color; import java.awt.ruponent; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class BoxLayoutDemo {

 private static JComponent createComponent(String s) {
   JLabel l = new JLabel(s);
   l.setBorder(BorderFactory
       .createMatteBorder(5, 5, 5, 5, Color.DARK_GRAY));
   l.setHorizontalAlignment(JLabel.CENTER);
   l.setAlignmentX(Component.CENTER_ALIGNMENT); //use middle of row
   return l;
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JPanel p = new JPanel();
   p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
   p.add(createComponent("Component 1"));
   p.add(Box.createVerticalGlue());
   p.add(createComponent("Component 2"));
   p.add(createComponent("Component 3"));
   p.add(createComponent("Component 4"));
   frame.setContentPane(p);
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



BoxLayout: Glue Sample

   <source lang="java">
   

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class GlueSample {

 public static void main(String args[]) {
   Box horizontalBox;
   JPanel panel;
   JFrame frame = new JFrame("Horizontal Glue");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container contentPane = frame.getContentPane();
   contentPane.setLayout(new GridLayout(0, 1));
   horizontalBox = Box.createHorizontalBox();
   horizontalBox.add(Box.createGlue());
   horizontalBox.add(new JButton("Left"));
   horizontalBox.add(new JButton("Middle"));
   horizontalBox.add(new JButton("Right"));
   panel = new JPanel(new BorderLayout());
   panel.add(horizontalBox);
   panel.setBorder(BorderFactory.createTitledBorder("Beginning Glue"));
   contentPane.add(panel);
   horizontalBox = Box.createHorizontalBox();
   horizontalBox.add(new JButton("Left"));
   horizontalBox.add(Box.createGlue());
   horizontalBox.add(new JButton("Middle"));
   horizontalBox.add(Box.createGlue());
   horizontalBox.add(new JButton("Right"));
   panel = new JPanel(new BorderLayout());
   panel.add(horizontalBox);
   panel.setBorder(BorderFactory.createTitledBorder("2 Middle Glues"));
   contentPane.add(panel);
   horizontalBox = Box.createHorizontalBox();
   horizontalBox.add(Box.createGlue());
   horizontalBox.add(new JButton("Left"));
   horizontalBox.add(new JButton("Middle"));
   horizontalBox.add(new JButton("Right"));
   horizontalBox.add(Box.createGlue());
   panel = new JPanel(new BorderLayout());
   panel.add(horizontalBox);
   panel
       .setBorder(BorderFactory
           .createTitledBorder("Beginning/End Glues"));
   contentPane.add(panel);
   horizontalBox = Box.createHorizontalBox();
   horizontalBox.add(new JButton("Left"));
   horizontalBox.add(new JButton("Middle"));
   horizontalBox.add(new JButton("Right"));
   panel = new JPanel(new BorderLayout());
   horizontalBox.add(Box.createGlue());
   panel.add(horizontalBox);
   panel.setBorder(BorderFactory.createTitledBorder("End Glue"));
   contentPane.add(panel);
   frame.setSize(300, 300);
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



Box layout manager using the Box utility class

   <source lang="java">
   

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// HBoxWithStrut.java //Another test of the box layout manager using the Box utility class. //This version separates several components with a fixed width gap. // import java.awt.Button; import javax.swing.Box; import javax.swing.JFrame; public class HBoxWithStrut extends JFrame {

 public HBoxWithStrut() {
   super("Box & Strut Frame");
   setSize(370, 80);
   Box box = Box.createHorizontalBox();
   setContentPane(box);
   for (int i = 0; i < 3; i++) {
     Button b = new Button("B" + i);
     box.add(b);
   }
   // Add a spacer between the first three buttons and the last three
   box.add(Box.createHorizontalStrut(10));
   for (int i = 3; i < 6; i++) {
     Button b = new Button("B" + i);
     box.add(b);
   }
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   setVisible(true);
 }
 public static void main(String args[]) {
   HBoxWithStrut bt = new HBoxWithStrut();
 }

}



 </source>
   
  
 
  



BoxLayout Pane

   <source lang="java">
   

/*

* Copyright (c) 2000 David Flanagan. All rights reserved. This code is from the
* book Java Examples in a Nutshell, 2nd Edition. It is provided AS-IS, WITHOUT
* ANY WARRANTY either expressed or implied. You may study, use, and modify it
* for any non-commercial purpose. You may distribute it non-commercially as
* long as you retain this notice. For a commercial use license, or to purchase
* the book (recommended), visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; public class BoxLayoutPane extends JPanel {

 public BoxLayoutPane() {
   // Use a BorderLayout layout manager to arrange various Box components
   this.setLayout(new BorderLayout());
   // Give the entire panel a margin by adding an empty border
   // We could also do this by overriding getInsets()
   this.setBorder(new EmptyBorder(10, 10, 10, 10));
   // Add a plain row of buttons along the top of the pane
   Box row = Box.createHorizontalBox();
   for (int i = 0; i < 4; i++) {
     JButton b = new JButton("B" + i);
     b.setFont(new Font("serif", Font.BOLD, 12 + i * 2));
     row.add(b);
   }
   this.add(row, BorderLayout.NORTH);
   // Add a plain column of buttons along the right edge
   // Use BoxLayout with a different kind of Swing container
   // Give the column a border: can"t do this with the Box class
   JPanel col = new JPanel();
   col.setLayout(new BoxLayout(col, BoxLayout.Y_AXIS));
   col.setBorder(new TitledBorder(new EtchedBorder(), "Column"));
   for (int i = 0; i < 4; i++) {
     JButton b = new JButton("Button " + i);
     b.setFont(new Font("sanserif", Font.BOLD, 10 + i * 2));
     col.add(b);
   }
   this.add(col, BorderLayout.EAST); // Add column to right of panel
   // Add a button box along the bottom of the panel.
   // Use "Glue" to space the buttons evenly
   Box buttonbox = Box.createHorizontalBox();
   buttonbox.add(Box.createHorizontalGlue()); // stretchy space
   buttonbox.add(new JButton("Okay"));
   buttonbox.add(Box.createHorizontalGlue()); // stretchy space
   buttonbox.add(new JButton("Cancel"));
   buttonbox.add(Box.createHorizontalGlue()); // stretchy space
   buttonbox.add(new JButton("Help"));
   buttonbox.add(Box.createHorizontalGlue()); // stretchy space
   this.add(buttonbox, BorderLayout.SOUTH);
   // Create a component to display in the center of the panel
   JTextArea textarea = new JTextArea();
   textarea.setText("This component has 12-pixel margins on left and top"
       + " and has 72-pixel margins on right and bottom.");
   textarea.setLineWrap(true);
   textarea.setWrapStyleWord(true);
   // Use Box objects to give the JTextArea an unusual spacing
   // First, create a column with 3 kids. The first and last kids
   // are rigid spaces. The middle kid is the text area
   Box fixedcol = Box.createVerticalBox();
   fixedcol.add(Box.createVerticalStrut(12)); // 12 rigid pixels
   fixedcol.add(textarea); // Component fills in the rest
   fixedcol.add(Box.createVerticalStrut(72)); // 72 rigid pixels
   // Now create a row. Give it rigid spaces on the left and right,
   // and put the column from above in the middle.
   Box fixedrow = Box.createHorizontalBox();
   fixedrow.add(Box.createHorizontalStrut(12));
   fixedrow.add(fixedcol);
   fixedrow.add(Box.createHorizontalStrut(72));
   // Now add the JTextArea in the column in the row to the panel
   this.add(fixedrow, BorderLayout.CENTER);
 }
 public static void main(String[] a) {
   JFrame f = new JFrame();
   f.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   f.setContentPane(new BoxLayoutPane());
   f.pack();
   f.setVisible(true);
 }

}




 </source>
   
  
 
  



BoxLayout Sample

   <source lang="java">
   

import java.awt.BorderLayout; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class BoxLayoutSample {

 public static void main(String args[]) {
   JFrame verticalFrame = new JFrame("Vertical");
   verticalFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Box verticalBox = Box.createVerticalBox();
   verticalBox.add(new JLabel("Top"));
   verticalBox.add(new JTextField("Middle"));
   verticalBox.add(new JButton("Bottom"));
   verticalFrame.getContentPane().add(verticalBox, BorderLayout.CENTER);
   verticalFrame.setSize(150, 150);
   verticalFrame.setVisible(true);
   JFrame horizontalFrame = new JFrame("Horizontal");
   Box horizontalBox = Box.createHorizontalBox();
   horizontalBox.add(new JLabel("Left"));
   horizontalBox.add(new JTextField("Middle"));
   horizontalBox.add(new JButton("Right"));
   horizontalFrame.getContentPane()
       .add(horizontalBox, BorderLayout.CENTER);
   horizontalFrame.setSize(150, 150);
   horizontalFrame.setVisible(true);
 }

}



 </source>
   
  
 
  



BoxLayout: setAlignmentX setAlignmentY

   <source lang="java">
   

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.ruponent; import java.awt.Container; import java.awt.Dimension; import java.util.Enumeration; import java.util.Vector; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; public class BoxSample {

 public static void main(String args[]) {
   JButton button;
   Vector buttons = new Vector();
   Dimension dim;
   JFrame frame = new JFrame("Box Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container contentPane = frame.getContentPane();
   contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS));
   JPanel topLeft = new JPanel();
   topLeft.setLayout(new BoxLayout(topLeft, BoxLayout.X_AXIS));
   topLeft.add(button = new JButton("One"));
   buttons.add(button);
   changeBoth(button);
   topLeft.add(button = new JButton("Two"));
   buttons.add(button);
   changeBoth(button);
   changeWidth(topLeft);
   JPanel bottomLeft = new JPanel();
   bottomLeft.setLayout(new BoxLayout(bottomLeft, BoxLayout.X_AXIS));
   bottomLeft.add(button = new JButton("Six"));
   buttons.add(button);
   changeBoth(button);
   bottomLeft.add(button = new JButton("Seven"));
   buttons.add(button);
   changeBoth(button);
   changeWidth(bottomLeft);
   JPanel left = new JPanel();
   left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS));
   left.add(topLeft);
   left.add(button = new JButton("Four"));
   buttons.add(button);
   changeBoth(button);
   left.add(bottomLeft);
   changeBoth(left);
   JPanel right = new JPanel();
   right.setLayout(new BoxLayout(right, BoxLayout.Y_AXIS));
   right.add(button = new JButton("Three"));
   buttons.add(button);
   changeWidth(button);
   right.add(button = new JButton("Five"));
   buttons.add(button);
   changeBoth(button);
   changeBoth(right);
   contentPane.add(left);
   contentPane.add(right);
   tweak(buttons);
   frame.pack();
   frame.setVisible(true);
 }
 private static void changeWidth(JComponent comp) {
   comp.setAlignmentX(Component.CENTER_ALIGNMENT);
   comp.setAlignmentY(Component.CENTER_ALIGNMENT);
   Dimension dim = comp.getPreferredSize();
   dim.width = Integer.MAX_VALUE;
   comp.setMaximumSize(dim);
 }
 private static void changeHeight(JComponent comp) {
   comp.setAlignmentX(Component.CENTER_ALIGNMENT);
   comp.setAlignmentY(Component.CENTER_ALIGNMENT);
   Dimension dim = comp.getPreferredSize();
   dim.height = Integer.MAX_VALUE;
   comp.setMaximumSize(dim);
 }
 private static void changeBoth(JComponent comp) {
   comp.setAlignmentX(Component.CENTER_ALIGNMENT);
   comp.setAlignmentY(Component.CENTER_ALIGNMENT);
   Dimension dim = new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
   comp.setMaximumSize(dim);
 }
 private static void tweak(Vector buttons) {
   // calc max preferred width
   JButton button;
   Dimension dim;
   int maxWidth = 0;
   Enumeration e = buttons.elements();
   while (e.hasMoreElements()) {
     button = (JButton) e.nextElement();
     dim = button.getPreferredSize();
     if (dim.width > maxWidth)
       maxWidth = dim.width;
   }
   // set max preferred width
   e = buttons.elements();
   while (e.hasMoreElements()) {
     button = (JButton) e.nextElement();
     dim = button.getPreferredSize();
     dim.width = maxWidth;
     button.setPreferredSize(dim);
   }
 }

}



 </source>
   
  
 
  



BoxLayout X Y alignment

   <source lang="java">
   

import java.awt.BorderLayout; import java.awt.Button; import java.awt.Container; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; public class YAxisAlignXButton {

 private static Container makeIt(String title) {
   String labels[] = { "--", "----", "--------", "------------" };
   JPanel container = new JPanel();
   container.setBorder(BorderFactory.createTitledBorder(title));
   BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
   container.setLayout(layout);
   for (int i = 0, n = labels.length; i < n; i++) {
     Button button = new Button(labels[i]);
     // Use default alignment - same for all
     container.add(button);
   }
   return container;
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Alignment Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container panel = makeIt("AWT Button");
   Container contentPane = frame.getContentPane();
   contentPane.add(panel, BorderLayout.CENTER);
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



CardLayout Demo

   <source lang="java">
   

import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; public class CardLayoutDemo implements ActionListener {

   JPanel cards; //a panel that uses CardLayout
   final static String[] strings = 
       {"Component 1", 
        "Component 2 is so long-winded it makes the container wide", 
        "Component 3"};
   private static JComponent createComponent(String s) {
       JLabel l = new JLabel(s);
       l.setBorder(BorderFactory.createMatteBorder(5,5,5,5,
                                                   Color.DARK_GRAY));
       l.setHorizontalAlignment(JLabel.CENTER);
       return l;
   }
   public void addCardsToPane(Container pane) {
       JRadioButton[] rb = new JRadioButton[strings.length];
       ButtonGroup group = new ButtonGroup();
       JPanel buttons = new JPanel();
       buttons.setLayout(new BoxLayout(buttons,
                                       BoxLayout.PAGE_AXIS));
       
       for (int i= 0; i < strings.length; i++) {
           rb[i] = new JRadioButton("Show component #" + (i+1));
           rb[i].setActionCommand(String.valueOf(i));
           rb[i].addActionListener(this);
           group.add(rb[i]);
           buttons.add(rb[i]);
       }
       rb[0].setSelected(true);
       
       //Create the panel that contains the "cards".
       cards = new JPanel(new CardLayout());
       for (int i = 0; i < strings.length; i++) {
           cards.add(createComponent(strings[i]), String.valueOf(i));
       }
       pane.add(buttons, BorderLayout.NORTH);
       pane.add(cards, BorderLayout.CENTER);
   }
   public void actionPerformed(ActionEvent evt) {
       CardLayout cl = (CardLayout)(cards.getLayout());
       cl.show(cards, (String)evt.getActionCommand());
   }
   public static void main(String[] args) {
       JFrame.setDefaultLookAndFeelDecorated(true);
       JFrame frame = new JFrame();
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       CardLayoutDemo demo = new CardLayoutDemo();
       demo.addCardsToPane(frame.getContentPane());
       frame.pack();
       frame.setVisible(true);
   }

}



 </source>
   
  
 
  



Component Alignment

   <source lang="java">
   

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.ruponent; import java.awt.Container; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Insets; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class YAxisDiffAlign {

 private static Container makeIt(String title, boolean more) {
   JPanel container = new JPanel() {
     public void paintComponent(Graphics g) {
       super.paintComponent(g);
       Insets insets = getInsets();
       int width = getWidth() - insets.left - insets.right;
       int halfWidth = width / 2 + insets.left;
       int height = getHeight();
       int halfHeight = height / 2 + insets.top;
       g.drawLine(halfWidth, 0, halfWidth, height);
     }
   };
   container.setBorder(BorderFactory.createTitledBorder(title));
   BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
   container.setLayout(layout);
   JButton button;
   button = new JButton("0.0");
   button.setOpaque(false);
   button.setAlignmentX(Component.LEFT_ALIGNMENT);
   container.add(button);
   if (more) {
     button = new JButton(".25");
     button.setOpaque(false);
     button.setAlignmentX(0.25f);
     container.add(button);
     button = new JButton(".5");
     button.setOpaque(false);
     button.setAlignmentX(Component.CENTER_ALIGNMENT);
     container.add(button);
     button = new JButton(".75");
     button.setOpaque(false);
     button.setAlignmentX(0.75f);
     container.add(button);
   }
   button = new JButton("1.0");
   button.setOpaque(false);
   button.setAlignmentX(Component.RIGHT_ALIGNMENT);
   container.add(button);
   return container;
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Alignment Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container panel1 = makeIt("Mixed", false);
   Container panel2 = makeIt("Mixed", true);
   Container contentPane = frame.getContentPane();
   contentPane.setLayout(new GridLayout(1, 2));
   contentPane.add(panel1);
   contentPane.add(panel2);
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



Demonstrates BorderLayout

   <source lang="java">
   

// : c14:BorderLayout1.java // Demonstrates BorderLayout. //<applet code=BorderLayout1 width=300 height=250></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; public class BorderLayout1 extends JApplet {

 public void init() {
   Container cp = getContentPane();
   cp.add(BorderLayout.NORTH, new JButton("North"));
   cp.add(BorderLayout.SOUTH, new JButton("South"));
   cp.add(BorderLayout.EAST, new JButton("East"));
   cp.add(BorderLayout.WEST, new JButton("West"));
   cp.add(BorderLayout.CENTER, new JButton("Center"));
 }
 public static void main(String[] args) {
   run(new BorderLayout1(), 300, 250);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~




 </source>
   
  
 
  



Demonstrates FlowLayout

   <source lang="java">
   

// : c14:FlowLayout1.java // Demonstrates FlowLayout. // <applet code=FlowLayout1 width=300 height=250></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.Container; import java.awt.FlowLayout; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; public class FlowLayout1 extends JApplet {

 public void init() {
   Container cp = getContentPane();
   cp.setLayout(new FlowLayout());
   for (int i = 0; i < 20; i++)
     cp.add(new JButton("Button " + i));
 }
 public static void main(String[] args) {
   run(new FlowLayout1(), 300, 250);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~




 </source>
   
  
 
  



Demonstrates GridLayout

   <source lang="java">
   

// : c14:GridLayout1.java // Demonstrates GridLayout. // <applet code=GridLayout1 width=300 height=250></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.Container; import java.awt.GridLayout; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; public class GridLayout1 extends JApplet {

 public void init() {
   Container cp = getContentPane();
   cp.setLayout(new GridLayout(7, 3));
   for (int i = 0; i < 20; i++)
     cp.add(new JButton("Button " + i));
 }
 public static void main(String[] args) {
   run(new GridLayout1(), 300, 250);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~




 </source>
   
  
 
  



FlowLayout Pane

   <source lang="java">
   

/*

* Copyright (c) 2000 David Flanagan. All rights reserved. This code is from the
* book Java Examples in a Nutshell, 2nd Edition. It is provided AS-IS, WITHOUT
* ANY WARRANTY either expressed or implied. You may study, use, and modify it
* for any non-commercial purpose. You may distribute it non-commercially as
* long as you retain this notice. For a commercial use license, or to purchase
* the book (recommended), visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class FlowLayoutPane extends JPanel {

 public FlowLayoutPane() {
   // Use a FlowLayout layout manager. Left justify rows.
   // Leave 10 pixels of horizontal and vertical space between components.
   this.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
   // Add some buttons to demonstrate the layout.
   String spaces = ""; // Used to make the buttons different
   for (int i = 1; i <= 9; i++) {
     this.add(new JButton("Button #" + i + spaces));
     spaces += " ";
   }
   // Give ourselves a default size
   this.setPreferredSize(new Dimension(500, 200));
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame();
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   frame.getContentPane().add(new FlowLayoutPane(), BorderLayout.CENTER);
   // Finally, set the size of the main window, and pop it up.
   frame.setSize(600, 400);
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



GridLayout Demo

   <source lang="java">
   

import java.awt.Color; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class GridLayoutDemo {

 private static JComponent createComponent(String s) {
   JLabel l = new JLabel(s);
   l.setBorder(BorderFactory
       .createMatteBorder(5, 5, 5, 5, Color.DARK_GRAY));
   l.setHorizontalAlignment(JLabel.CENTER);
   return l;
 }
 public static void main(String[] args) {
   JFrame.setDefaultLookAndFeelDecorated(true);
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JPanel p = new JPanel(new GridLayout(1, 0));
   p.add(createComponent("Component 1"));
   p.add(createComponent("Component 2"));
   p.add(createComponent("Component 3"));
   p.add(createComponent("Component 4"));
   frame.setContentPane(p);
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



GridLayout Demo 3

   <source lang="java">
   

import java.awt.ruponent; import java.awt.Container; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class XAxisAlignY {

 private static Container makeIt(String title, float alignment) {
   String labels[] = { "--", "--", "--" };
   JPanel container = new JPanel();
   container.setBorder(BorderFactory.createTitledBorder(title));
   BoxLayout layout = new BoxLayout(container, BoxLayout.X_AXIS);
   container.setLayout(layout);
   for (int i = 0, n = labels.length; i < n; i++) {
     JButton button = new JButton(labels[i]);
     button.setAlignmentY(alignment);
     container.add(button);
   }
   return container;
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Alignment Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container panel1 = makeIt("Top", Component.TOP_ALIGNMENT);
   Container panel2 = makeIt("Center", Component.CENTER_ALIGNMENT);
   Container panel3 = makeIt("Bottom", Component.BOTTOM_ALIGNMENT);
   Container contentPane = frame.getContentPane();
   contentPane.setLayout(new GridLayout(1, 3));
   contentPane.add(panel1);
   contentPane.add(panel2);
   contentPane.add(panel3);
   frame.setSize(423, 171);
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



GridLayout Pane

   <source lang="java">
   

/*

* Copyright (c) 2000 David Flanagan. All rights reserved. This code is from the
* book Java Examples in a Nutshell, 2nd Edition. It is provided AS-IS, WITHOUT
* ANY WARRANTY either expressed or implied. You may study, use, and modify it
* for any non-commercial purpose. You may distribute it non-commercially as
* long as you retain this notice. For a commercial use license, or to purchase
* the book (recommended), visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class GridLayoutPane extends JPanel {

 public GridLayoutPane() {
   // Layout components into a grid three columns wide, with the number
   // of rows depending on the number of components. Leave 10 pixels
   // of horizontal and vertical space between components
   this.setLayout(new GridLayout(0, 3, 10, 10));
   // Add some components
   for (int i = 1; i <= 12; i++)
     this.add(new JButton("Button #" + i));
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame();
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   frame.getContentPane().add(new GridLayoutPane(), BorderLayout.CENTER);
   // Finally, set the size of the main window, and pop it up.
   frame.setSize(600, 400);
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



Laying Out a Screen with CardLayout

   <source lang="java">
   

import java.awt.CardLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class CardLayoutTest {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Card Layout");
   final Container contentPane = frame.getContentPane();
   final CardLayout layout = new CardLayout();
   contentPane.setLayout(layout);
   ActionListener listener = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       layout.next(contentPane);
     }
   };
   for (int i = 0; i < 5; i++) {
     String label = "Card " + i;
     JButton button = new JButton(label);
     contentPane.add(button, label);
     button.addActionListener(listener);
   }
   frame.setSize(300, 200);
   frame.show();
 }

}



 </source>
   
  
 
  



Laying out a screen with SpringLayout

   <source lang="java">
   

import java.awt.ruponent; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SpringLayout; public class SpringFormTest {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Spring");
   Container contentPane = frame.getContentPane();
   SpringLayout layout = new SpringLayout();
   contentPane.setLayout(layout);
   Component left = new JLabel("Left");
   Component right = new JTextField(15);
   contentPane.add(left);
   contentPane.add(right);
   layout.putConstraint(SpringLayout.WEST, left, 10, SpringLayout.WEST,
       contentPane);
   layout.putConstraint(SpringLayout.NORTH, left, 25, SpringLayout.NORTH,
       contentPane);
   layout.putConstraint(SpringLayout.NORTH, right, 25, SpringLayout.NORTH,
       contentPane);
   layout.putConstraint(SpringLayout.WEST, right, 20, SpringLayout.EAST,
       left);
   frame.setSize(300, 100);
   frame.show();
 }

}



 </source>
   
  
 
  



Laying Out Components in a Flow (Left-to-Right, Top-to-Bottom)

   <source lang="java">
  

import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JPanel; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component1 = new JButton();
   JButton component2 = new JButton();
   int align = FlowLayout.CENTER; // or LEFT, RIGHT
   JPanel panel = new JPanel(new FlowLayout(align));
   panel.add(component1);
   panel.add(component2);
 }

}


 </source>
   
  
 
  



Laying Out Components in a Grid

   <source lang="java">
  

import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JPanel; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component1 = new JButton();
   JButton component2 = new JButton();
   
   int rows = 2;
   int cols = 2;
   JPanel panel = new JPanel(new GridLayout(rows, cols));
   panel.add(component1);
   panel.add(component2);
 }

}


 </source>
   
  
 
  



Laying Out Components Using Absolute Coordinates

   <source lang="java">
   

import javax.swing.JButton; import javax.swing.JPanel; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component = new JButton();
   JPanel panel = new JPanel(null);
   component.setBounds(1, 1, 100, 100);
   panel.add(component);
 }

}



 </source>
   
  
 
  



Layout: Overlay Sample

   <source lang="java">
   

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.OverlayLayout; public class OverlaySample {

 public static final String SET_MINIMUM = "Minimum";
 public static final String SET_MAXIMUM = "Maximum";
 public static final String SET_CENTRAL = "Central";
 public static final String SET_MIXED = "Mixed";
 static JButton smallButton = new JButton();
 static JButton mediumButton = new JButton();
 static JButton largeButton = new JButton();
 public static void setupButtons(String command) {
   if (SET_MINIMUM.equals(command)) {
     smallButton.setAlignmentX(0.0f);
     smallButton.setAlignmentY(0.0f);
     mediumButton.setAlignmentX(0.0f);
     mediumButton.setAlignmentY(0.0f);
     largeButton.setAlignmentX(0.0f);
     largeButton.setAlignmentY(0.0f);
   } else if (SET_MAXIMUM.equals(command)) {
     smallButton.setAlignmentX(1.0f);
     smallButton.setAlignmentY(1.0f);
     mediumButton.setAlignmentX(1.0f);
     mediumButton.setAlignmentY(1.0f);
     largeButton.setAlignmentX(1.0f);
     largeButton.setAlignmentY(1.0f);
   } else if (SET_CENTRAL.equals(command)) {
     smallButton.setAlignmentX(0.5f);
     smallButton.setAlignmentY(0.5f);
     mediumButton.setAlignmentX(0.5f);
     mediumButton.setAlignmentY(0.5f);
     largeButton.setAlignmentX(0.5f);
     largeButton.setAlignmentY(0.5f);
   } else if (SET_MIXED.equals(command)) {
     smallButton.setAlignmentX(0.0f);
     smallButton.setAlignmentY(0.0f);
     mediumButton.setAlignmentX(0.5f);
     mediumButton.setAlignmentY(0.5f);
     largeButton.setAlignmentX(1.0f);
     largeButton.setAlignmentY(1.0f);
   } else {
     throw new IllegalArgumentException("Illegal Command: " + command);
   }
   // Redraw panel
   ((JPanel) largeButton.getParent()).revalidate();
 }
 public static void main(String args[]) {
   ActionListener generalActionListener = new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       JComponent comp = (JComponent) actionEvent.getSource();
       System.out.println(actionEvent.getActionCommand() + ": "
           + comp.getBounds());
     }
   };
   ActionListener sizingActionListener = new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       setupButtons(actionEvent.getActionCommand());
     }
   };
   JFrame frame = new JFrame("Overlay Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JPanel panel = new JPanel();
   LayoutManager overlay = new OverlayLayout(panel);
   panel.setLayout(overlay);
   Object settings[][] = {
       { "Small", new Dimension(25, 25), Color.white },
       { "Medium", new Dimension(50, 50), Color.gray },
       { "Large", new Dimension(100, 100), Color.black } };
   JButton buttons[] = { smallButton, mediumButton, largeButton };
   for (int i = 0, n = settings.length; i < n; i++) {
     JButton button = buttons[i];
     button.addActionListener(generalActionListener);
     button.setActionCommand((String) settings[i][0]);
     button.setMaximumSize((Dimension) settings[i][1]);
     button.setBackground((Color) settings[i][2]);
     panel.add(button);
   }
   setupButtons(SET_CENTRAL);
   JPanel actionPanel = new JPanel();
   actionPanel.setBorder(BorderFactory
       .createTitledBorder("Change Alignment"));
   String actionSettings[] = { SET_MINIMUM, SET_MAXIMUM, SET_CENTRAL,
       SET_MIXED };
   for (int i = 0, n = actionSettings.length; i < n; i++) {
     JButton button = new JButton(actionSettings[i]);
     button.addActionListener(sizingActionListener);
     actionPanel.add(button);
   }
   Container contentPane = frame.getContentPane();
   contentPane.add(panel, BorderLayout.CENTER);
   contentPane.add(actionPanel, BorderLayout.SOUTH);
   frame.setSize(400, 300);
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



NullLayout Pane

   <source lang="java">
   

/*

* Copyright (c) 2000 David Flanagan. All rights reserved. This code is from the
* book Java Examples in a Nutshell, 2nd Edition. It is provided AS-IS, WITHOUT
* ANY WARRANTY either expressed or implied. You may study, use, and modify it
* for any non-commercial purpose. You may distribute it non-commercially as
* long as you retain this notice. For a commercial use license, or to purchase
* the book (recommended), visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class NullLayoutPane extends JPanel {

 public NullLayoutPane() {
   // Get rid of the default layout manager.
   // We"ll arrange the components ourselves.
   this.setLayout(null);
   // Create some buttons and set their sizes and positions explicitly
   for (int i = 1; i <= 9; i++) {
     JButton b = new JButton("Button #" + i);
     b.setBounds(i * 30, i * 20, 125, 30); // use reshape() in Java 1.0
     this.add(b);
   }
 }
 // Specify how big the panel should be.
 public Dimension getPreferredSize() {
   return new Dimension(425, 250);
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame();
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   frame.getContentPane().add(new NullLayoutPane(), BorderLayout.CENTER);
   // Finally, set the size of the main window, and pop it up.
   frame.setSize(600, 400);
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



Rigid areas are like pairs of struts

   <source lang="java">
   

// : c14:Box4.java // Rigid areas are like pairs of struts. // <applet code=Box4 width=450 height=300></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.Dimension; import javax.swing.Box; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; public class Box4 extends JApplet {

 public void init() {
   Box bv = Box.createVerticalBox();
   bv.add(new JButton("Top"));
   bv.add(Box.createRigidArea(new Dimension(120, 90)));
   bv.add(new JButton("Bottom"));
   Box bh = Box.createHorizontalBox();
   bh.add(new JButton("Left"));
   bh.add(Box.createRigidArea(new Dimension(160, 80)));
   bh.add(new JButton("Right"));
   bv.add(bh);
   getContentPane().add(bv);
 }
 public static void main(String[] args) {
   run(new Box4(), 450, 300);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~




 </source>
   
  
 
  



Simpler CardLayout demo

   <source lang="java">
   

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Button; import java.awt.CardLayout; import java.awt.Label; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /**

* Simpler CardLayout demo: cycles through some labels.
* 
* @author Ian Darwin
* @version $Id: CardLayDemo1.java,v 1.3 2004/03/21 00:44:36 ian Exp $
*/

public class CardLayDemo1 extends Applet {

 CardLayout cardlay;
 Panel panel;
 Button b1;
 int cardno = 0;
 final int NCARDS = 4;
 String labels[] = new String[NCARDS];
 public void init() {
   panel = new Panel();
   cardlay = new CardLayout();
   b1 = new Button("Next");
   b1.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
       if (++cardno >= NCARDS)
         cardno = 0;
       cardlay.show(panel, labels[cardno]);
     }
   });
   labels[0] = "Card One";
   labels[1] = "Card Two";
   labels[2] = "Card Three";
   labels[3] = "Card Four";
   panel.setLayout(cardlay);
   for (int i = 0; i < NCARDS; i++)
     panel.add(labels[i], new Label(labels[i]));
   cardlay.show(panel, labels[0]);
   setLayout(new BorderLayout());
   add("Center", panel);
   add("South", b1);
 }

}




 </source>
   
  
 
  



Spring Compact Grid

   <source lang="java">
   

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* A 1.4 application that uses SpringLayout to create a compact grid. Other
* files required: SpringUtilities.java.
*/

import java.awt.ruponent; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.Spring; import javax.swing.SpringLayout; public class SpringCompactGrid {

 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   JPanel panel = new JPanel(new SpringLayout());
   int rows = 10;
   int cols = 10;
   for (int r = 0; r < rows; r++) {
     for (int c = 0; c < cols; c++) {
       int anInt = (int) Math.pow(r, c);
       JTextField textField = new JTextField(Integer.toString(anInt));
       panel.add(textField);
     }
   }
   //Lay out the panel.
   SpringUtilities.makeCompactGrid(panel, //parent
       rows, cols, 3, 3, //initX, initY
       3, 3); //xPad, yPad
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("SpringCompactGrid");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Set up the content pane.
   panel.setOpaque(true); //content panes must be opaque
   frame.setContentPane(panel);
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   //Schedule a job for the event-dispatching thread:
   //creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }

} /**

* A 1.4 file that provides utility methods for creating form- or grid-style
* layouts with SpringLayout. These utilities are used by several programs, such
* as SpringBox and SpringCompactGrid.
*/

class SpringUtilities {

 /**
  * A debugging utility that prints to stdout the component"s minimum,
  * preferred, and maximum sizes.
  */
 public static void printSizes(Component c) {
   System.out.println("minimumSize = " + c.getMinimumSize());
   System.out.println("preferredSize = " + c.getPreferredSize());
   System.out.println("maximumSize = " + c.getMaximumSize());
 }
 /**
  * Aligns the first rows*cols components of
  * parent in a grid. Each component is as big as the maximum
  * preferred width and height of the components. The parent is made just big
  * enough to fit them all.
  * 
  * @param rows
  *            number of rows
  * @param cols
  *            number of columns
  * @param initialX
  *            x location to start the grid at
  * @param initialY
  *            y location to start the grid at
  * @param xPad
  *            x padding between cells
  * @param yPad
  *            y padding between cells
  */
 public static void makeGrid(Container parent, int rows, int cols,
     int initialX, int initialY, int xPad, int yPad) {
   SpringLayout layout;
   try {
     layout = (SpringLayout) parent.getLayout();
   } catch (ClassCastException exc) {
     System.err
         .println("The first argument to makeGrid must use SpringLayout.");
     return;
   }
   Spring xPadSpring = Spring.constant(xPad);
   Spring yPadSpring = Spring.constant(yPad);
   Spring initialXSpring = Spring.constant(initialX);
   Spring initialYSpring = Spring.constant(initialY);
   int max = rows * cols;
   //Calculate Springs that are the max of the width/height so that all
   //cells have the same size.
   Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0))
       .getWidth();
   Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0))
       .getWidth();
   for (int i = 1; i < max; i++) {
     SpringLayout.Constraints cons = layout.getConstraints(parent
         .getComponent(i));
     maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth());
     maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight());
   }
   //Apply the new width/height Spring. This forces all the
   //components to have the same size.
   for (int i = 0; i < max; i++) {
     SpringLayout.Constraints cons = layout.getConstraints(parent
         .getComponent(i));
     cons.setWidth(maxWidthSpring);
     cons.setHeight(maxHeightSpring);
   }
   //Then adjust the x/y constraints of all the cells so that they
   //are aligned in a grid.
   SpringLayout.Constraints lastCons = null;
   SpringLayout.Constraints lastRowCons = null;
   for (int i = 0; i < max; i++) {
     SpringLayout.Constraints cons = layout.getConstraints(parent
         .getComponent(i));
     if (i % cols == 0) { //start of new row
       lastRowCons = lastCons;
       cons.setX(initialXSpring);
     } else { //x position depends on previous component
       cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST),
           xPadSpring));
     }
     if (i / cols == 0) { //first row
       cons.setY(initialYSpring);
     } else { //y position depends on previous row
       cons.setY(Spring.sum(lastRowCons
           .getConstraint(SpringLayout.SOUTH), yPadSpring));
     }
     lastCons = cons;
   }
   //Set the parent"s size.
   SpringLayout.Constraints pCons = layout.getConstraints(parent);
   pCons.setConstraint(SpringLayout.SOUTH, Spring.sum(Spring
       .constant(yPad), lastCons.getConstraint(SpringLayout.SOUTH)));
   pCons.setConstraint(SpringLayout.EAST, Spring.sum(
       Spring.constant(xPad), lastCons
           .getConstraint(SpringLayout.EAST)));
 }
 /* Used by makeCompactGrid. */
 private static SpringLayout.Constraints getConstraintsForCell(int row,
     int col, Container parent, int cols) {
   SpringLayout layout = (SpringLayout) parent.getLayout();
   Component c = parent.getComponent(row * cols + col);
   return layout.getConstraints(c);
 }
 /**
  * Aligns the first rows*cols components of
  * parent in a grid. Each component in a column is as wide as
  * the maximum preferred width of the components in that column; height is
  * similarly determined for each row. The parent is made just big enough to
  * fit them all.
  * 
  * @param rows
  *            number of rows
  * @param cols
  *            number of columns
  * @param initialX
  *            x location to start the grid at
  * @param initialY
  *            y location to start the grid at
  * @param xPad
  *            x padding between cells
  * @param yPad
  *            y padding between cells
  */
 public static void makeCompactGrid(Container parent, int rows, int cols,
     int initialX, int initialY, int xPad, int yPad) {
   SpringLayout layout;
   try {
     layout = (SpringLayout) parent.getLayout();
   } catch (ClassCastException exc) {
     System.err
         .println("The first argument to makeCompactGrid must use SpringLayout.");
     return;
   }
   //Align all cells in each column and make them the same width.
   Spring x = Spring.constant(initialX);
   for (int c = 0; c < cols; c++) {
     Spring width = Spring.constant(0);
     for (int r = 0; r < rows; r++) {
       width = Spring.max(width, getConstraintsForCell(r, c, parent,
           cols).getWidth());
     }
     for (int r = 0; r < rows; r++) {
       SpringLayout.Constraints constraints = getConstraintsForCell(r,
           c, parent, cols);
       constraints.setX(x);
       constraints.setWidth(width);
     }
     x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
   }
   //Align all cells in each row and make them the same height.
   Spring y = Spring.constant(initialY);
   for (int r = 0; r < rows; r++) {
     Spring height = Spring.constant(0);
     for (int c = 0; c < cols; c++) {
       height = Spring.max(height, getConstraintsForCell(r, c, parent,
           cols).getHeight());
     }
     for (int c = 0; c < cols; c++) {
       SpringLayout.Constraints constraints = getConstraintsForCell(r,
           c, parent, cols);
       constraints.setY(y);
       constraints.setHeight(height);
     }
     y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
   }
   //Set the parent"s size.
   SpringLayout.Constraints pCons = layout.getConstraints(parent);
   pCons.setConstraint(SpringLayout.SOUTH, y);
   pCons.setConstraint(SpringLayout.EAST, x);
 }

}



 </source>
   
  
 
  



Spring Demo 1

   <source lang="java">
   

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.Container; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SpringLayout; public class SpringDemo1 {

 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("SpringDemo1");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Set up the content pane.
   Container contentPane = frame.getContentPane();
   SpringLayout layout = new SpringLayout();
   contentPane.setLayout(layout);
   contentPane.add(new JLabel("Label: "));
   contentPane.add(new JTextField("Text field", 15));
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   //Schedule a job for the event-dispatching thread:
   //creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }

}



 </source>
   
  
 
  



Spring Demo 2

   <source lang="java">
   

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.Container; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SpringLayout; public class SpringDemo2 {

 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("SpringDemo2");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Set up the content pane.
   Container contentPane = frame.getContentPane();
   SpringLayout layout = new SpringLayout();
   contentPane.setLayout(layout);
   //Create and add the components.
   JLabel label = new JLabel("Label: ");
   JTextField textField = new JTextField("Text field", 15);
   contentPane.add(label);
   contentPane.add(textField);
   //Adjust constraints for the label so it"s at (5,5).
   layout.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.WEST,
       contentPane);
   layout.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.NORTH,
       contentPane);
   //Adjust constraints for the text field so it"s at
   //(<label"s right edge> + 5, 5).
   layout.putConstraint(SpringLayout.WEST, textField, 5,
       SpringLayout.EAST, label);
   layout.putConstraint(SpringLayout.NORTH, textField, 5,
       SpringLayout.NORTH, contentPane);
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   //Schedule a job for the event-dispatching thread:
   //creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }

}



 </source>
   
  
 
  



Spring Demo 3

   <source lang="java">
   

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.Container; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SpringLayout; public class SpringDemo3 {

 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("SpringDemo3");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Set up the content pane.
   Container contentPane = frame.getContentPane();
   SpringLayout layout = new SpringLayout();
   contentPane.setLayout(layout);
   //Create and add the components.
   JLabel label = new JLabel("Label: ");
   JTextField textField = new JTextField("Text field", 15);
   contentPane.add(label);
   contentPane.add(textField);
   //Adjust constraints for the label so it"s at (5,5).
   layout.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.WEST,
       contentPane);
   layout.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.NORTH,
       contentPane);
   //Adjust constraints for the text field so it"s at
   //(<label"s right edge> + 5, 5).
   layout.putConstraint(SpringLayout.WEST, textField, 5,
       SpringLayout.EAST, label);
   layout.putConstraint(SpringLayout.NORTH, textField, 5,
       SpringLayout.NORTH, contentPane);
   //Adjust constraints for the content pane: Its right
   //edge should be 5 pixels beyond the text field"s right
   //edge, and its bottom edge should be 5 pixels beyond
   //the bottom edge of the tallest component (which we"ll
   //assume is textField).
   layout.putConstraint(SpringLayout.EAST, contentPane, 5,
       SpringLayout.EAST, textField);
   layout.putConstraint(SpringLayout.SOUTH, contentPane, 5,
       SpringLayout.SOUTH, textField);
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   //Schedule a job for the event-dispatching thread:
   //creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }

}



 </source>
   
  
 
  



Spring Demo 4

   <source lang="java">
   

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.ruponent; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.Spring; import javax.swing.SpringLayout; public class SpringDemo4 {

 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("SpringDemo4");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Set up the content pane.
   Container contentPane = frame.getContentPane();
   SpringLayout layout = new SpringLayout();
   contentPane.setLayout(layout);
   //Create and add the components.
   JLabel label = new JLabel("Label: ");
   JTextField textField = new JTextField("Text field", 15);
   contentPane.add(label);
   contentPane.add(textField);
   //Adjust constraints for the label so it"s at (5,5).
   SpringLayout.Constraints labelCons = layout.getConstraints(label);
   labelCons.setX(Spring.constant(5));
   labelCons.setY(Spring.constant(5));
   //Adjust constraints for the text field so it"s at
   //(<label"s right edge> + 5, 5).
   SpringLayout.Constraints textFieldCons = layout
       .getConstraints(textField);
   textFieldCons.setX(Spring.sum(Spring.constant(5), labelCons
       .getConstraint(SpringLayout.EAST)));
   textFieldCons.setY(Spring.constant(5));
   //Adjust constraints for the content pane.
   setContainerSize(contentPane, 5);
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   //Schedule a job for the event-dispatching thread:
   //creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }
 public static void setContainerSize(Container parent, int pad) {
   SpringLayout layout = (SpringLayout) parent.getLayout();
   Component[] components = parent.getComponents();
   Spring maxHeightSpring = Spring.constant(0);
   SpringLayout.Constraints pCons = layout.getConstraints(parent);
   //Set the container"s right edge to the right edge
   //of its rightmost component + padding.
   Component rightmost = components[components.length - 1];
   SpringLayout.Constraints rCons = layout.getConstraints(rightmost);
   pCons.setConstraint(SpringLayout.EAST, Spring.sum(Spring.constant(pad),
       rCons.getConstraint(SpringLayout.EAST)));
   //Set the container"s bottom edge to the bottom edge
   //of its tallest component + padding.
   for (int i = 0; i < components.length; i++) {
     SpringLayout.Constraints cons = layout
         .getConstraints(components[i]);
     maxHeightSpring = Spring.max(maxHeightSpring, cons
         .getConstraint(SpringLayout.SOUTH));
   }
   pCons.setConstraint(SpringLayout.SOUTH, Spring.sum(
       Spring.constant(pad), maxHeightSpring));
 }

}



 </source>
   
  
 
  



Spring Form

   <source lang="java">
   

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* A 1.4 application that uses SpringLayout to create a forms-type layout. Other
* files required: SpringUtilities.java.
*/

import java.awt.ruponent; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.Spring; import javax.swing.SpringLayout; public class SpringForm {

 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   String[] labels = { "Name: ", "Fax: ", "Email: ", "Address: " };
   int numPairs = labels.length;
   //Create and populate the panel.
   JPanel p = new JPanel(new SpringLayout());
   for (int i = 0; i < numPairs; i++) {
     JLabel l = new JLabel(labels[i], JLabel.TRAILING);
     p.add(l);
     JTextField textField = new JTextField(10);
     l.setLabelFor(textField);
     p.add(textField);
   }
   //Lay out the panel.
   SpringUtilities.makeCompactGrid(p, numPairs, 2, //rows, cols
       6, 6, //initX, initY
       6, 6); //xPad, yPad
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("SpringForm");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Set up the content pane.
   p.setOpaque(true); //content panes must be opaque
   frame.setContentPane(p);
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   //Schedule a job for the event-dispatching thread:
   //creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }

} /**

* A 1.4 file that provides utility methods for creating form- or grid-style
* layouts with SpringLayout. These utilities are used by several programs, such
* as SpringBox and SpringCompactGrid.
*/

class SpringUtilities {

 /**
  * A debugging utility that prints to stdout the component"s minimum,
  * preferred, and maximum sizes.
  */
 public static void printSizes(Component c) {
   System.out.println("minimumSize = " + c.getMinimumSize());
   System.out.println("preferredSize = " + c.getPreferredSize());
   System.out.println("maximumSize = " + c.getMaximumSize());
 }
 /**
  * Aligns the first rows*cols components of
  * parent in a grid. Each component is as big as the maximum
  * preferred width and height of the components. The parent is made just big
  * enough to fit them all.
  * 
  * @param rows
  *            number of rows
  * @param cols
  *            number of columns
  * @param initialX
  *            x location to start the grid at
  * @param initialY
  *            y location to start the grid at
  * @param xPad
  *            x padding between cells
  * @param yPad
  *            y padding between cells
  */
 public static void makeGrid(Container parent, int rows, int cols,
     int initialX, int initialY, int xPad, int yPad) {
   SpringLayout layout;
   try {
     layout = (SpringLayout) parent.getLayout();
   } catch (ClassCastException exc) {
     System.err
         .println("The first argument to makeGrid must use SpringLayout.");
     return;
   }
   Spring xPadSpring = Spring.constant(xPad);
   Spring yPadSpring = Spring.constant(yPad);
   Spring initialXSpring = Spring.constant(initialX);
   Spring initialYSpring = Spring.constant(initialY);
   int max = rows * cols;
   //Calculate Springs that are the max of the width/height so that all
   //cells have the same size.
   Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0))
       .getWidth();
   Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0))
       .getWidth();
   for (int i = 1; i < max; i++) {
     SpringLayout.Constraints cons = layout.getConstraints(parent
         .getComponent(i));
     maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth());
     maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight());
   }
   //Apply the new width/height Spring. This forces all the
   //components to have the same size.
   for (int i = 0; i < max; i++) {
     SpringLayout.Constraints cons = layout.getConstraints(parent
         .getComponent(i));
     cons.setWidth(maxWidthSpring);
     cons.setHeight(maxHeightSpring);
   }
   //Then adjust the x/y constraints of all the cells so that they
   //are aligned in a grid.
   SpringLayout.Constraints lastCons = null;
   SpringLayout.Constraints lastRowCons = null;
   for (int i = 0; i < max; i++) {
     SpringLayout.Constraints cons = layout.getConstraints(parent
         .getComponent(i));
     if (i % cols == 0) { //start of new row
       lastRowCons = lastCons;
       cons.setX(initialXSpring);
     } else { //x position depends on previous component
       cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST),
           xPadSpring));
     }
     if (i / cols == 0) { //first row
       cons.setY(initialYSpring);
     } else { //y position depends on previous row
       cons.setY(Spring.sum(lastRowCons
           .getConstraint(SpringLayout.SOUTH), yPadSpring));
     }
     lastCons = cons;
   }
   //Set the parent"s size.
   SpringLayout.Constraints pCons = layout.getConstraints(parent);
   pCons.setConstraint(SpringLayout.SOUTH, Spring.sum(Spring
       .constant(yPad), lastCons.getConstraint(SpringLayout.SOUTH)));
   pCons.setConstraint(SpringLayout.EAST, Spring.sum(
       Spring.constant(xPad), lastCons
           .getConstraint(SpringLayout.EAST)));
 }
 /* Used by makeCompactGrid. */
 private static SpringLayout.Constraints getConstraintsForCell(int row,
     int col, Container parent, int cols) {
   SpringLayout layout = (SpringLayout) parent.getLayout();
   Component c = parent.getComponent(row * cols + col);
   return layout.getConstraints(c);
 }
 /**
  * Aligns the first rows*cols components of
  * parent in a grid. Each component in a column is as wide as
  * the maximum preferred width of the components in that column; height is
  * similarly determined for each row. The parent is made just big enough to
  * fit them all.
  * 
  * @param rows
  *            number of rows
  * @param cols
  *            number of columns
  * @param initialX
  *            x location to start the grid at
  * @param initialY
  *            y location to start the grid at
  * @param xPad
  *            x padding between cells
  * @param yPad
  *            y padding between cells
  */
 public static void makeCompactGrid(Container parent, int rows, int cols,
     int initialX, int initialY, int xPad, int yPad) {
   SpringLayout layout;
   try {
     layout = (SpringLayout) parent.getLayout();
   } catch (ClassCastException exc) {
     System.err
         .println("The first argument to makeCompactGrid must use SpringLayout.");
     return;
   }
   //Align all cells in each column and make them the same width.
   Spring x = Spring.constant(initialX);
   for (int c = 0; c < cols; c++) {
     Spring width = Spring.constant(0);
     for (int r = 0; r < rows; r++) {
       width = Spring.max(width, getConstraintsForCell(r, c, parent,
           cols).getWidth());
     }
     for (int r = 0; r < rows; r++) {
       SpringLayout.Constraints constraints = getConstraintsForCell(r,
           c, parent, cols);
       constraints.setX(x);
       constraints.setWidth(width);
     }
     x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
   }
   //Align all cells in each row and make them the same height.
   Spring y = Spring.constant(initialY);
   for (int r = 0; r < rows; r++) {
     Spring height = Spring.constant(0);
     for (int c = 0; c < cols; c++) {
       height = Spring.max(height, getConstraintsForCell(r, c, parent,
           cols).getHeight());
     }
     for (int c = 0; c < cols; c++) {
       SpringLayout.Constraints constraints = getConstraintsForCell(r,
           c, parent, cols);
       constraints.setY(y);
       constraints.setHeight(height);
     }
     y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
   }
   //Set the parent"s size.
   SpringLayout.Constraints pCons = layout.getConstraints(parent);
   pCons.setConstraint(SpringLayout.SOUTH, y);
   pCons.setConstraint(SpringLayout.EAST, x);
 }

}



 </source>
   
  
 
  



SpringLayout Utilities

   <source lang="java">
   

/*

* (c) Copyright 2004 by Heng Yuan
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* ITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/

import java.awt.*; import javax.swing.*; /**

* This code is from 
* The source is at http://java.sun.ru/docs/books/tutorial/uiswing/layout/example-1dot4/SpringUtilities.java.
* No copyright or license information was in the source file and it was from the tutorial.  Thus
* assuming I could use it in this program.  Below is the original file header.  The file is
* not modified other than reformating white spaces.
*

* A 1.4 file that provides utility methods for * creating form- or grid-style layouts with SpringLayout. * These utilities are used by several programs, such as * SpringBox and SpringCompactGrid. *

* TODO: Although algorithm wise is correct, this class fails to address the problem of rounding
* errors.  As the result, sometimes the last row can be mismatched with other rows.  The solution
* to the problem is to force the alignment of edges.
*
* @see javax.swing.SpringLayout
* @see cookxml.cookswing.creator.SpringGridCreator
* @author Heng Yuan
* @version $Id: SpringLayoutUtilities.java 215 2007-06-06 03:59:41Z coconut $
* @since CookSwing 1.0
*/

public class SpringLayoutUtilities {

 /**
  * A debugging utility that prints to stdout the component"s
  * minimum, preferred, and maximum sizes.
  */
 public static void printSizes (Component c)
 {
   System.out.println ("minimumSize = " + c.getMinimumSize ());
   System.out.println ("preferredSize = " + c.getPreferredSize ());
   System.out.println ("maximumSize = " + c.getMaximumSize ());
 }
 /**
  * Aligns the first rows * cols
  * components of parent in
  * a grid. Each component is as big as the maximum
  * preferred width and height of the components.
  * The parent is made just big enough to fit them all.
  *
  * @param rows     number of rows
  * @param cols     number of columns
  * @param initialX x location to start the grid at
  * @param initialY y location to start the grid at
  * @param xPad     x padding between cells
  * @param yPad     y padding between cells
  */
 public static void makeGrid (Container parent,
                int rows, int cols,
                int initialX, int initialY,
                int xPad, int yPad)
 {
   SpringLayout layout;
   try
   {
     layout = (SpringLayout)parent.getLayout ();
   }
   catch (ClassCastException exc)
   {
     System.err.println ("The first argument to makeGrid must use SpringLayout.");
     return;
   }
   Spring xPadSpring = Spring.constant (xPad);
   Spring yPadSpring = Spring.constant (yPad);
   Spring initialXSpring = Spring.constant (initialX);
   Spring initialYSpring = Spring.constant (initialY);
   int max = rows * cols;
   //Calculate Springs that are the max of the width/height so that all
   //cells have the same size.
   Spring maxWidthSpring = layout.getConstraints (parent.getComponent (0)).
       getWidth ();
   Spring maxHeightSpring = layout.getConstraints (parent.getComponent (0)).
       getWidth ();
   for (int i = 1; i < max; i++)
   {
     SpringLayout.Constraints cons = layout.getConstraints (parent.getComponent (i));
     maxWidthSpring = Spring.max (maxWidthSpring, cons.getWidth ());
     maxHeightSpring = Spring.max (maxHeightSpring, cons.getHeight ());
   }
   //Apply the new width/height Spring. This forces all the
   //components to have the same size.
   for (int i = 0; i < max; i++)
   {
     SpringLayout.Constraints cons = layout.getConstraints (parent.getComponent (i));
     cons.setWidth (maxWidthSpring);
     cons.setHeight (maxHeightSpring);
   }
   //Then adjust the x/y constraints of all the cells so that they
   //are aligned in a grid.
   SpringLayout.Constraints lastCons = null;
   SpringLayout.Constraints lastRowCons = null;
   for (int i = 0; i < max; i++)
   {
     SpringLayout.Constraints cons = layout.getConstraints (parent.getComponent (i));
     if (i % cols == 0)
     { //start of new row
       lastRowCons = lastCons;
       cons.setX (initialXSpring);
     }
     else
     { //x position depends on previous component
       cons.setX (Spring.sum (lastCons.getConstraint (SpringLayout.EAST),
                    xPadSpring));
     }
     if (i / cols == 0)
     { //first row
       cons.setY (initialYSpring);
     }
     else
     { //y position depends on previous row
       cons.setY (Spring.sum (lastRowCons.getConstraint (SpringLayout.SOUTH),
                    yPadSpring));
     }
     lastCons = cons;
   }
   //Set the parent"s size.
   SpringLayout.Constraints pCons = layout.getConstraints (parent);
   pCons.setConstraint (SpringLayout.SOUTH,
              Spring.sum (Spring.constant (yPad),
                    lastCons.getConstraint (SpringLayout.SOUTH)));
   pCons.setConstraint (SpringLayout.EAST,
              Spring.sum (Spring.constant (xPad),
                    lastCons.getConstraint (SpringLayout.EAST)));
 }
 /* Used by makeCompactGrid. */
 private static SpringLayout.Constraints getConstraintsForCell (int row, int col,
                                  Container parent,
                                  int cols)
 {
   SpringLayout layout = (SpringLayout)parent.getLayout ();
   Component c = parent.getComponent (row * cols + col);
   return layout.getConstraints (c);
 }
 /**
  * Aligns the first rows * cols
  * components of parent in
  * a grid. Each component in a column is as wide as the maximum
  * preferred width of the components in that column;
  * height is similarly determined for each row.
  * The parent is made just big enough to fit them all.
  *
  * @param rows     number of rows
  * @param cols     number of columns
  * @param initialX x location to start the grid at
  * @param initialY y location to start the grid at
  * @param xPad     x padding between cells
  * @param yPad     y padding between cells
  */
 public static void makeCompactGrid (Container parent,
                   int rows, int cols,
                   int initialX, int initialY,
                   int xPad, int yPad)
 {
   SpringLayout layout;
   try
   {
     layout = (SpringLayout)parent.getLayout ();
   }
   catch (ClassCastException exc)
   {
     System.err.println ("The first argument to makeCompactGrid must use SpringLayout.");
     return;
   }
   //Align all cells in each column and make them the same width.
   Spring x = Spring.constant (initialX);
   for (int c = 0; c < cols; c++)
   {
     Spring width = Spring.constant (0);
     for (int r = 0; r < rows; r++)
     {
       width = Spring.max (width,
                 getConstraintsForCell (r, c, parent, cols).
                 getWidth ());
     }
     for (int r = 0; r < rows; r++)
     {
       SpringLayout.Constraints constraints =
           getConstraintsForCell (r, c, parent, cols);
       constraints.setX (x);
       constraints.setWidth (width);
     }
     x = Spring.sum (x, Spring.sum (width, Spring.constant (xPad)));
   }
   //Align all cells in each row and make them the same height.
   Spring y = Spring.constant (initialY);
   for (int r = 0; r < rows; r++)
   {
     Spring height = Spring.constant (0);
     for (int c = 0; c < cols; c++)
     {
       height = Spring.max (height,
                  getConstraintsForCell (r, c, parent, cols).
                  getHeight ());
     }
     for (int c = 0; c < cols; c++)
     {
       SpringLayout.Constraints constraints =
           getConstraintsForCell (r, c, parent, cols);
       constraints.setY (y);
       constraints.setHeight (height);
     }
     y = Spring.sum (y, Spring.sum (height, Spring.constant (yPad)));
   }
   //Set the parent"s size.
   SpringLayout.Constraints pCons = layout.getConstraints (parent);
   pCons.setConstraint (SpringLayout.SOUTH, y);
   pCons.setConstraint (SpringLayout.EAST, x);
 }

}



 </source>
   
  
 
  



Use FlowLayout to hold checkBox, Label and TextField

   <source lang="java">
  

import java.awt.Button; import java.awt.Checkbox; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Label; import java.awt.List; import java.awt.TextField; public class Main {

 public static void main(String[] args) {
   Frame f = new Frame("FlowLayout demo");
   f.setLayout(new FlowLayout());
   f.add(new Button("Red"));
   f.add(new Button("Blue"));
   f.add(new Button("White"));
   List list = new List();
   for (int i = 0; i < args.length; i++) {
     list.add(args[i]);
   }
   f.add(list);
   f.add(new Checkbox("Pick me", true));
   f.add(new Label("Enter name here:"));
   f.add(new TextField(20));
   f.pack();
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



Use SpringLayout to create a single row of components

   <source lang="java">
   

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* A 1.4 application that uses SpringLayout to create a single row of
* components, similar to that produced by a horizontal BoxLayout. Other files
* required: SpringUtilities.java.
*/

import java.awt.ruponent; import java.awt.Container; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.Spring; import javax.swing.SpringLayout; public class SpringBox {

 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("SpringBox");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Set up the content pane.
   Container contentPane = frame.getContentPane();
   contentPane.setLayout(new SpringLayout());
   //Add the buttons.
   contentPane.add(new JButton("Button 1"));
   contentPane.add(new JButton("Button 2"));
   contentPane.add(new JButton("Button 3"));
   contentPane.add(new JButton("Long-Named Button 4"));
   contentPane.add(new JButton("5"));
   //Lay out the buttons in one row and as many columns
   //as necessary, with 6 pixels of padding all around.
   SpringUtilities.makeCompactGrid(contentPane, 1, contentPane
       .getComponentCount(), 6, 6, 6, 6);
   //Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   //Schedule a job for the event-dispatching thread:
   //creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }

} /**

* A 1.4 file that provides utility methods for creating form- or grid-style
* layouts with SpringLayout. These utilities are used by several programs, such
* as SpringBox and SpringCompactGrid.
*/

class SpringUtilities {

 /**
  * A debugging utility that prints to stdout the component"s minimum,
  * preferred, and maximum sizes.
  */
 public static void printSizes(Component c) {
   System.out.println("minimumSize = " + c.getMinimumSize());
   System.out.println("preferredSize = " + c.getPreferredSize());
   System.out.println("maximumSize = " + c.getMaximumSize());
 }
 /**
  * Aligns the first rows*cols components of
  * parent in a grid. Each component is as big as the maximum
  * preferred width and height of the components. The parent is made just big
  * enough to fit them all.
  * 
  * @param rows
  *            number of rows
  * @param cols
  *            number of columns
  * @param initialX
  *            x location to start the grid at
  * @param initialY
  *            y location to start the grid at
  * @param xPad
  *            x padding between cells
  * @param yPad
  *            y padding between cells
  */
 public static void makeGrid(Container parent, int rows, int cols,
     int initialX, int initialY, int xPad, int yPad) {
   SpringLayout layout;
   try {
     layout = (SpringLayout) parent.getLayout();
   } catch (ClassCastException exc) {
     System.err
         .println("The first argument to makeGrid must use SpringLayout.");
     return;
   }
   Spring xPadSpring = Spring.constant(xPad);
   Spring yPadSpring = Spring.constant(yPad);
   Spring initialXSpring = Spring.constant(initialX);
   Spring initialYSpring = Spring.constant(initialY);
   int max = rows * cols;
   //Calculate Springs that are the max of the width/height so that all
   //cells have the same size.
   Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0))
       .getWidth();
   Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0))
       .getWidth();
   for (int i = 1; i < max; i++) {
     SpringLayout.Constraints cons = layout.getConstraints(parent
         .getComponent(i));
     maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth());
     maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight());
   }
   //Apply the new width/height Spring. This forces all the
   //components to have the same size.
   for (int i = 0; i < max; i++) {
     SpringLayout.Constraints cons = layout.getConstraints(parent
         .getComponent(i));
     cons.setWidth(maxWidthSpring);
     cons.setHeight(maxHeightSpring);
   }
   //Then adjust the x/y constraints of all the cells so that they
   //are aligned in a grid.
   SpringLayout.Constraints lastCons = null;
   SpringLayout.Constraints lastRowCons = null;
   for (int i = 0; i < max; i++) {
     SpringLayout.Constraints cons = layout.getConstraints(parent
         .getComponent(i));
     if (i % cols == 0) { //start of new row
       lastRowCons = lastCons;
       cons.setX(initialXSpring);
     } else { //x position depends on previous component
       cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST),
           xPadSpring));
     }
     if (i / cols == 0) { //first row
       cons.setY(initialYSpring);
     } else { //y position depends on previous row
       cons.setY(Spring.sum(lastRowCons
           .getConstraint(SpringLayout.SOUTH), yPadSpring));
     }
     lastCons = cons;
   }
   //Set the parent"s size.
   SpringLayout.Constraints pCons = layout.getConstraints(parent);
   pCons.setConstraint(SpringLayout.SOUTH, Spring.sum(Spring
       .constant(yPad), lastCons.getConstraint(SpringLayout.SOUTH)));
   pCons.setConstraint(SpringLayout.EAST, Spring.sum(
       Spring.constant(xPad), lastCons
           .getConstraint(SpringLayout.EAST)));
 }
 /* Used by makeCompactGrid. */
 private static SpringLayout.Constraints getConstraintsForCell(int row,
     int col, Container parent, int cols) {
   SpringLayout layout = (SpringLayout) parent.getLayout();
   Component c = parent.getComponent(row * cols + col);
   return layout.getConstraints(c);
 }
 /**
  * Aligns the first rows*cols components of
  * parent in a grid. Each component in a column is as wide as
  * the maximum preferred width of the components in that column; height is
  * similarly determined for each row. The parent is made just big enough to
  * fit them all.
  * 
  * @param rows
  *            number of rows
  * @param cols
  *            number of columns
  * @param initialX
  *            x location to start the grid at
  * @param initialY
  *            y location to start the grid at
  * @param xPad
  *            x padding between cells
  * @param yPad
  *            y padding between cells
  */
 public static void makeCompactGrid(Container parent, int rows, int cols,
     int initialX, int initialY, int xPad, int yPad) {
   SpringLayout layout;
   try {
     layout = (SpringLayout) parent.getLayout();
   } catch (ClassCastException exc) {
     System.err
         .println("The first argument to makeCompactGrid must use SpringLayout.");
     return;
   }
   //Align all cells in each column and make them the same width.
   Spring x = Spring.constant(initialX);
   for (int c = 0; c < cols; c++) {
     Spring width = Spring.constant(0);
     for (int r = 0; r < rows; r++) {
       width = Spring.max(width, getConstraintsForCell(r, c, parent,
           cols).getWidth());
     }
     for (int r = 0; r < rows; r++) {
       SpringLayout.Constraints constraints = getConstraintsForCell(r,
           c, parent, cols);
       constraints.setX(x);
       constraints.setWidth(width);
     }
     x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
   }
   //Align all cells in each row and make them the same height.
   Spring y = Spring.constant(initialY);
   for (int r = 0; r < rows; r++) {
     Spring height = Spring.constant(0);
     for (int c = 0; c < cols; c++) {
       height = Spring.max(height, getConstraintsForCell(r, c, parent,
           cols).getHeight());
     }
     for (int c = 0; c < cols; c++) {
       SpringLayout.Constraints constraints = getConstraintsForCell(r,
           c, parent, cols);
       constraints.setY(y);
       constraints.setHeight(height);
     }
     y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
   }
   //Set the parent"s size.
   SpringLayout.Constraints pCons = layout.getConstraints(parent);
   pCons.setConstraint(SpringLayout.SOUTH, y);
   pCons.setConstraint(SpringLayout.EAST, x);
 }

}



 </source>
   
  
 
  



Using CardLayout

   <source lang="java">
  

import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.FlowLayout; import java.awt.Label; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; class CardFrame extends JFrame implements ActionListener {

 JButton nextCard = new JButton("Next Card >");
 JButton prevCard = new JButton("< Previous Card");
 JButton firstCard = new JButton("<< First Card");
 JButton lastCard = new JButton("Last Card >>");
 JPanel cardPanel = new JPanel();
 CardLayout cardLayout = new CardLayout(10, 10);
 public CardFrame(String title) {
   setLayout(new BorderLayout(10, 10));
   nextCard.addActionListener(this);
   prevCard.addActionListener(this);
   firstCard.addActionListener(this);
   lastCard.addActionListener(this);
   Panel buttonsPanel = new Panel(new FlowLayout(FlowLayout.CENTER));
   buttonsPanel.add(firstCard);
   buttonsPanel.add(prevCard);
   buttonsPanel.add(nextCard);
   buttonsPanel.add(lastCard);
   setCardLayout();
   add(BorderLayout.CENTER, cardPanel);
   add(BorderLayout.NORTH, buttonsPanel);
 }
 private void setCardLayout() {
   cardPanel.setLayout(cardLayout);
   Label one = new Label("CARD 1", Label.CENTER);
   Label two = new Label("CARD 2", Label.CENTER);
   Label three = new Label("CARD 3", Label.CENTER);
   Label four = new Label("CARD 4", Label.CENTER);
   Label five = new Label("CARD 5", Label.CENTER);
   cardPanel.add(one, "one");
   cardPanel.add(two, "two");
   cardPanel.add(three, "three");
   cardPanel.add(four, "four");
   cardPanel.add(five, "five");
   cardLayout.show(cardPanel, "one");
 }
 public void actionPerformed(ActionEvent ae) {
   if (ae.getSource().equals(nextCard)) {
     cardLayout.next(cardPanel);
   } else if (ae.getSource().equals(prevCard)) {
     cardLayout.previous(cardPanel);
   } else if (ae.getSource().equals(lastCard)) {
     cardLayout.last(cardPanel);
   } else if (ae.getSource().equals(firstCard)) {
     cardLayout.first(cardPanel);
   }
 }

}


 </source>
   
  
 
  



Using Glue

   <source lang="java">
   

// : c14:Box3.java // Using Glue. // <applet code=Box3 width=450 height=300></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import javax.swing.Box; import javax.swing.JApplet; import javax.swing.JFrame; import javax.swing.JLabel; public class Box3 extends JApplet {

 public void init() {
   Box bv = Box.createVerticalBox();
   bv.add(new JLabel("Hello"));
   bv.add(Box.createVerticalGlue());
   bv.add(new JLabel("Applet"));
   bv.add(Box.createVerticalGlue());
   bv.add(new JLabel("World"));
   Box bh = Box.createHorizontalBox();
   bh.add(new JLabel("Hello"));
   bh.add(Box.createHorizontalGlue());
   bh.add(new JLabel("Applet"));
   bh.add(Box.createHorizontalGlue());
   bh.add(new JLabel("World"));
   bv.add(Box.createVerticalGlue());
   bv.add(bh);
   bv.add(Box.createVerticalGlue());
   getContentPane().add(bv);
 }
 public static void main(String[] args) {
   run(new Box3(), 450, 300);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~




 </source>
   
  
 
  



Various layouts

   <source lang="java">
   

import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.TitledBorder; public class CommonLayouts extends JFrame {

 public CommonLayouts() {
   super("Common Layout Managers");
   setSize(500, 380);
   JPanel desktop = new JPanel();
   getContentPane().add(desktop);
   JPanel fr1 = new JPanel();
   fr1.setBorder(new TitledBorder("FlowLayout"));
   fr1.setLayout(new FlowLayout());
   fr1.add(new JButton("1"));
   fr1.add(new JButton("2"));
   fr1.add(new JButton("3"));
   fr1.add(new JButton("4"));
   desktop.add(fr1, 0);
   JPanel fr2 = new JPanel();
   fr2.setBorder(new TitledBorder("GridLayout"));
   fr2.setLayout(new GridLayout(2, 2));
   fr2.add(new JButton("1"));
   fr2.add(new JButton("2"));
   fr2.add(new JButton("3"));
   fr2.add(new JButton("4"));
   desktop.add(fr2, 0);
   JPanel fr3 = new JPanel();
   fr3.setBorder(new TitledBorder("BorderLayout"));
   fr3.add(new JButton("1"), BorderLayout.NORTH);
   fr3.add(new JButton("2"), BorderLayout.EAST);
   fr3.add(new JButton("3"), BorderLayout.SOUTH);
   fr3.add(new JButton("4"), BorderLayout.WEST);
   desktop.add(fr3, 0);
   JPanel fr4 = new JPanel();
   fr4.setBorder(new TitledBorder("BoxLayout - X"));
   fr4.setLayout(new BoxLayout(fr4, BoxLayout.X_AXIS));
   fr4.add(new JButton("1"));
   fr4.add(Box.createHorizontalStrut(12));
   fr4.add(new JButton("2"));
   fr4.add(Box.createGlue());
   fr4.add(new JButton("3"));
   fr4.add(Box.createHorizontalGlue());
   fr4.add(new JButton("4"));
   desktop.add(fr4, 0);
   JPanel fr5 = new JPanel();
   fr5.setBorder(new TitledBorder("BoxLayout - Y"));
   fr5.setLayout(new BoxLayout(fr5, BoxLayout.Y_AXIS));
   fr5.add(new JButton("1"));
   fr5.add(Box.createVerticalStrut(10));
   fr5.add(new JButton("2"));
   fr5.add(Box.createGlue());
   fr5.add(new JButton("3"));
   fr5.add(Box.createVerticalGlue());
   fr5.add(new JButton("4"));
   desktop.add(fr5, 0);
   WindowListener wndCloser = new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   };
   addWindowListener(wndCloser);
   setVisible(true);
 }
 public static void main(String argv[]) {
   new CommonLayouts();
 }

}




 </source>
   
  
 
  



Vertical and horizontal BoxLayouts

   <source lang="java">
   

// : c14:Box1.java // Vertical and horizontal BoxLayouts. // <applet code=Box1 width=450 height=200></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.BorderLayout; import java.awt.Container; import javax.swing.Box; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; public class Box1 extends JApplet {

 public void init() {
   Box bv = Box.createVerticalBox();
   for (int i = 0; i < 5; i++)
     bv.add(new JButton("bv " + i));
   Box bh = Box.createHorizontalBox();
   for (int i = 0; i < 5; i++)
     bh.add(new JButton("bh " + i));
   Container cp = getContentPane();
   cp.add(BorderLayout.EAST, bv);
   cp.add(BorderLayout.SOUTH, bh);
 }
 public static void main(String[] args) {
   run(new Box1(), 450, 200);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~




 </source>
   
  
 
  



Without layout manager, we position components using absolute values.

   <source lang="java">
  

import javax.swing.JButton; import javax.swing.JFrame; public class Absolute {

 public static void main(String[] args) {
   JFrame f = new JFrame();
   f.setLayout(null);
   JButton ok = new JButton("OK");
   ok.setBounds(50, 150, 80, 25);
   JButton close = new JButton("Close");
   close.setBounds(150, 150, 80, 25);
   f.add(ok);
   f.add(close);
   f.setSize(300, 250);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}


 </source>