SpringLayout
类根据一组约束定位其关联容器的子节点。
示例
package com.yiibai.swingdemo;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing SpringLayout示例");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
SpringLayout layout = new SpringLayout();
panel.setLayout(layout);
JLabel label = new JLabel("输入名称: ");
JTextField textField = new JTextField("", 15);
panel.add(label);
panel.add(textField);
layout.putConstraint(SpringLayout.WEST, label,5, SpringLayout.WEST, panel);
layout.putConstraint(SpringLayout.NORTH, label,5, SpringLayout.NORTH, panel);
layout.putConstraint(SpringLayout.WEST, textField,5, SpringLayout.EAST, label);
layout.putConstraint(SpringLayout.NORTH, textField,5, SpringLayout.NORTH, panel);
layout.putConstraint(SpringLayout.EAST, panel,5, SpringLayout.EAST, textField);
layout.putConstraint(SpringLayout.SOUTH, panel,5, SpringLayout.SOUTH, textField);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
执行上面示例代码,得到以下结果: