控制台程序。
可以把JFrame对象aWindow的内容面板的布局管理器设置为javax.swing.SpringLayout管理器。
SpringLayout类定义的布局管理器根据javax.swing.Spring对象定义的一组约束,决定容器中每个组件的位置和大小。在使用SpringLayout管理器的容器中,每个组件都有与之关联的SpringLayout.Constrains对象,Constrains对象定义了组件的4条边的位置。在访问组件对象关联的SpringLayout.Constrains对象之前,必须先把组件添加到容器中。
1 import javax.swing.*; 2 import java.awt.*; 3 4 public class TrySpringLayout { 5 6 public static void createWindow(){ 7 JFrame aWindow = new JFrame("This is the Window Title"); 8 Toolkit theKit = aWindow.getToolkit(); // Get the window toolkit 9 Dimension wndSize = theKit.getScreenSize(); // Get screen size 10 11 // Set the position to screen center & size to half screen size 12 aWindow.setSize(wndSize.width/2, wndSize.height/2); // Set window size 13 aWindow.setLocationRelativeTo(null); // Center window 14 aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 15 16 SpringLayout layout = new SpringLayout(); // Create a layout manager 17 Container content = aWindow.getContentPane(); // Get the content pane 18 content.setLayout(layout); // Set the container layout mgr 19 20 JButton[] buttons = new JButton[6]; // Array to store buttons 21 SpringLayout.Constraints constr = null; 22 for(int i = 0; i < buttons.length; ++i) { 23 buttons[i] = new JButton("Press " + (i+1)); 24 content.add(buttons[i]); // Add a Button to content pane 25 } 26 27 Spring xSpring = Spring.constant(5,15,25); // x constraint for first button 28 Spring ySpring = Spring.constant(10,30, 50); // y constraint for first button 29 30 // Connect x,y for first button to left and top of container by springs 31 constr = layout.getConstraints(buttons[0]); 32 constr.setX(xSpring); 33 constr.setY(ySpring); 34 35 // Hook buttons together with springs 36 for(int i = 1 ; i< buttons.length ; ++i) { 37 constr = layout.getConstraints(buttons[i]); 38 layout.putConstraint(SpringLayout.WEST, buttons[i], 39 xSpring,SpringLayout.EAST, buttons[i-1]); 40 layout.putConstraint(SpringLayout.NORTH, buttons[i], 41 ySpring,SpringLayout.SOUTH, buttons[i-1]); 42 } 43 // Uncomment the following code to constrain the content pane 44 /* 45 SpringLayout.Constraints constraint = layout.getConstraints(content); 46 constraint.setConstraint(SpringLayout.EAST, 47 Spring.sum(constr.getConstraint(SpringLayout.EAST), 48 Spring.constant(15))); 49 constraint.setConstraint(SpringLayout.SOUTH, 50 Spring.sum(constr.getConstraint(SpringLayout.SOUTH), 51 Spring.constant(10))); 52 aWindow.pack(); 53 */ 54 aWindow.setVisible(true); // Display the window 55 } 56 57 public static void main(String[] args) { 58 SwingUtilities.invokeLater(new Runnable() { 59 public void run() { 60 createWindow(); 61 } 62 }); 63 } 64 }
SpringLayout管理器非常灵活,如果对组件设置了合适的约束,就可以完成许多其他布局管理器的工作。