SpringLayout in Java Swing


 

SpringLayout in Java Swing

In this section, you will learn how to set component's layout using SpringLayout.

In this section, you will learn how to set component's layout using SpringLayout.

Java Swing SpringLayout Example

In this section, you will learn how to set component's layout using SpringLayout. It is a very flexible layout manager that can emulate many of the features of other layout managers. A SpringLayout lays out the components according to a set of constraints. Each constraint controls the vertical or horizontal distance between two component edges. The edges can belong to any component of the container, or to the container itself. Here we have created a simple form with SpringLayout.

Here is the code:


import java.awt.*;
import javax.swing.*;

public class SpringLayoutExample {
	public static void main(String args[]) {
		JFrame frame = new JFrame("SpringLayout");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container contentPane = frame.getContentPane();

		SpringLayout layout = new SpringLayout();
		contentPane.setLayout(layout);

		JLabel label = new JLabel("Enter Name");
		JTextField text = new JTextField(15);

		contentPane.add(label);
		contentPane.add(text);
		layout.putConstraint(SpringLayout.WEST, label, 10, SpringLayout.WEST,
				contentPane);
		layout.putConstraint(SpringLayout.NORTH, label, 25, SpringLayout.NORTH,
				contentPane);
		layout.putConstraint(SpringLayout.NORTH, text, 25, SpringLayout.NORTH,
				contentPane);
		layout.putConstraint(SpringLayout.WEST, text, 20, SpringLayout.EAST,
				label);

		frame.setSize(300, 100);
		frame.setVisible(true);
	}
}

Ads