Using a SpringLayout Manager : SpringLayout « Swing « Java Tutorial






Allows components to have their position defined by "springs" or "struts " fixed to an edge of the container or another component in the container.

Using a SpringLayout Manager
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Spring;
import javax.swing.SpringLayout;
public class TrySpringLayout {
  public static void main(String[] args) {
    JFrame aWindow = new JFrame("This is a Spring Layout");
    aWindow.setBounds(30, 30, 300, 300);
    aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    SpringLayout layout = new SpringLayout();
    Container content = aWindow.getContentPane();
    content.setLayout(layout);
    JButton[] buttons = new JButton[6];
    SpringLayout.Constraints constr = null;
    for (int i = 0; i < buttons.length; i++) {
      buttons[i] = new JButton("Press " + (i + 1));
      content.add(buttons[i]);
    }
    Spring xSpring = Spring.constant(5, 15, 25);
    Spring ySpring = Spring.constant(10, 30, 50);
    constr = layout.getConstraints(buttons[0]);
    constr.setX(xSpring);
    constr.setY(ySpring);
    // Hook buttons together with springs
    for (int i = 1; i < buttons.length; i++) {
      constr = layout.getConstraints(buttons[i]);
      layout.putConstraint(SpringLayout.WEST, buttons[i], xSpring, SpringLayout.EAST,
          buttons[i - 1]);
      layout.putConstraint(SpringLayout.NORTH, buttons[i], ySpring, SpringLayout.SOUTH,
          buttons[i - 1]);
    }
    aWindow.setVisible(true); // Display the window
  }
}








14.92.SpringLayout
14.92.1.SpringLayoutSpringLayout
14.92.2.How to Use SpringLayoutHow to Use SpringLayout
14.92.3.Specifying locations for each componentSpecifying locations for each component
14.92.4.Define the right (east) and bottom (south) edges of the containerDefine the right (east) and bottom (south) edges of the container
14.92.5.Using SpringLayout to lay out a gridUsing SpringLayout to lay out a grid
14.92.6.Using SpringLayout to create a compact gridUsing SpringLayout to create a compact grid
14.92.7.using SpringLayout to create a forms-type layoutusing SpringLayout to create a forms-type layout
14.92.8.Using SpringLayout to create a single rowUsing SpringLayout to create a single row
14.92.9.Using a SpringLayout ManagerUsing a SpringLayout Manager
14.92.10.Springs and Component SizeSprings and Component Size
14.92.11.SpringLayout Utilities