控制台程序。

可以把JFrame对象aWindow的内容面板的布局管理器设置为javax.swing.SpringLayout管理器。

SpringLayout类定义的布局管理器根据javax.swing.Spring对象定义的一组约束,决定容器中每个组件的位置和大小。在使用SpringLayout管理器的容器中,每个组件都有与之关联的SpringLayout.Constrains对象,Constrains对象定义了组件的4条边的位置。在访问组件对象关联的SpringLayout.Constrains对象之前,必须先把组件添加到容器中。

 import javax.swing.*;
import java.awt.*; public class TrySpringLayout { public static void createWindow(){
JFrame aWindow = new JFrame("This is the Window Title");
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.setSize(wndSize.width/2, wndSize.height/2); // Set window size
aWindow.setLocationRelativeTo(null); // Center window
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
SpringLayout.Constraints constr = null;
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
} Spring xSpring = Spring.constant(5,15,25); // x constraint for first button
Spring ySpring = Spring.constant(10,30, 50); // y constraint for first button // Connect x,y for first button to left and top of container by springs
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]);
}
// Uncomment the following code to constrain the content pane
/*
SpringLayout.Constraints constraint = layout.getConstraints(content);
constraint.setConstraint(SpringLayout.EAST,
Spring.sum(constr.getConstraint(SpringLayout.EAST),
Spring.constant(15)));
constraint.setConstraint(SpringLayout.SOUTH,
Spring.sum(constr.getConstraint(SpringLayout.SOUTH),
Spring.constant(10)));
aWindow.pack();
*/
aWindow.setVisible(true); // Display the window
} public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createWindow();
}
});
}
}

SpringLayout管理器非常灵活,如果对组件设置了合适的约束,就可以完成许多其他布局管理器的工作。

05-11 15:15