下面将针对SpringLayout布局管理器设计实例,实例代码如下所示:
public class BWF{
public static int WIDTH=300;
public static int HEIGHT=250;
public static void main(String args[]){
JFrame jf=new JFrame("测试SpringLayout布局管理器");
jf.setSize(WIDTH, HEIGHT);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane=new JPanel();
//创建了两个普通按钮组件、一个标签组件,将它们添加到中间容器中
JButton b1=new JButton("按钮1");
JButton b2=new JButton("按钮2");
JLabel l=new JLabel("测试程序");
contentPane.add(l);
contentPane.add(b1);
contentPane.add(b2);
//创建一个SpringLayout布局管理器,并且将之作为中间容器的布局方式
SpringLayout springLay=new SpringLayout();
contentPane.setLayout(springLay);
//针对每个组件设置其与边界的距离
springLay.putConstraint(SpringLayout.NORTH, l, 5, SpringLayout.NORTH, contentPane);
springLay.putConstraint(SpringLayout.WEST, l, 85, SpringLayout.WEST, contentPane);
springLay.putConstraint(SpringLayout.EAST, l, 85, SpringLayout.EAST, contentPane);
springLay.putConstraint(SpringLayout.NORTH, b1, 55, SpringLayout.NORTH, contentPane);
springLay.putConstraint(SpringLayout.WEST, b1, 5, SpringLayout.WEST, contentPane);
springLay.putConstraint(SpringLayout.EAST, b1, 25, SpringLayout.EAST, contentPane);
springLay.putConstraint(SpringLayout.NORTH, b2, 105, SpringLayout.NORTH, contentPane);
springLay.putConstraint(SpringLayout.WEST, b2, 5, SpringLayout.WEST, contentPane);
springLay.putConstraint(SpringLayout.EAST, b2, 25, SpringLayout.EAST, contentPane);
jf.setContentPane(contentPane);
jf.setVisible(true);
}
}
这个布局管理器是通过计算组件到边的距离来给组件布局的。比较前面几个布局管理器,GridBagLayout布局管理器和BoxLayout布局管理器比较人性化,而SpringLayout布局管理器虽然也比较人性化,但是比前面两种布局管理器要复杂的多。