Here's an example code snippet that demonstrates how to use SpringLayout in Java:
import javax.swing.*;
import java.awt.*;
public class SpringLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("SpringLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);
// Create components
JLabel nameLabel = new JLabel("Name:");
JTextField nameField = new JTextField(10);
JButton submitButton = new JButton("Submit");
// Add components to the content pane
contentPane.add(nameLabel);
contentPane.add(nameField);
contentPane.add(submitButton);
// Set constraints for components
layout.putConstraint(SpringLayout.WEST, nameLabel, 10, SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, nameLabel, 10, SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, nameField, 10, SpringLayout.EAST, nameLabel);
layout.putConstraint(SpringLayout.NORTH, nameField, 0, SpringLayout.NORTH, nameLabel);
layout.putConstraint(SpringLayout.WEST, submitButton, 0, SpringLayout.WEST, nameLabel);
layout.putConstraint(SpringLayout.NORTH, submitButton, 10, SpringLayout.SOUTH, nameLabel);
// Set the size and make the frame visible
frame.setSize(300, 200);
frame.setVisible(true);
}
}
This example creates a simple UI with a label, a text field, and a button. It uses SpringLayout to position these components within the container.