Java Reference
In-Depth Information
SpringLayout.Constraints newButtonConstr = layout.getConstraints(newButton);
layout.putConstraint(SpringLayout.WEST,
newButton,
xSpring,
SpringLayout.EAST,
button);
The first two arguments to the putConstraint() method for the layout object are the edge
specification and a reference to the dependent component respectively. The third argument is a Spring
object defining the constraint. The fourth and fifth arguments specify the edge and a reference to the
component to which the dependent component is anchored. Obviously, since constraints can only be
horizontal or vertical, both edges should have the same orientation. There is an overloaded version of
the putConstraint() method where the third argument is a value of type int that defines a fixed
distance between the edges.
Let's look at a simple example using a SpringLayout object as the layout manager.
Try It Out - Using a SpringLayout Manager
Here's the code for an example that displays six buttons in a window.
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SpringLayout;
import javax.swing.Spring;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
public class TrySpringLayout {
// The window object
static JFrame aWindow = new JFrame("This is a Spring Layout");
public static void main(String[] args) {
Toolkit theKit = aWindow.getToolkit(); // Get the window toolkit
Dimension wndSize = theKit.getScreenSize(); // Get screen size
// Set the position to screen center & size to half screen size
aWindow.setBounds(wndSize.width/4, wndSize.height/4, // Position
wndSize.width/2, wndSize.height/2); // Size
aWindow.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
SpringLayout layout = new SpringLayout(); // Create a layout manager
Container content = aWindow.getContentPane(); // Get the content pane
content.setLayout(layout); // Set the container layout mgr
JButton[] buttons = new JButton[6]; // Array to store buttons
for(int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("Press " + (i+1));
content.add(buttons[i]); // Add a Button to content pane
Search WWH ::




Custom Search