Java Swing Layout Managers: Types, Usage, and Examples
1. FlowLayout
- Description: Places components in a row, and starts a new row when the current row is full.
- Default for: JPanel
- Constructors:
* FlowLayout()
* FlowLayout(int align)
* FlowLayout(int align, int hgap, int vgap)
- Example:
JPanel panel = new JPanel(new FlowLayout());
panel.add(new JButton("Button1"));
2. BorderLayout
- Description: Arranges components in five regions: North, South, East, West, and Center.
- Default for: JFrame's content pane
- Constants: BorderLayout.NORTH, SOUTH, EAST, WEST, CENTER
- Example:
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
3. GridLayout
- Description: Arranges components in a grid with equal-sized cells.
- Constructors:
* GridLayout(int rows, int cols)
* GridLayout(int rows, int cols, int hgap, int vgap)
- Example:
panel.setLayout(new GridLayout(2, 2));
panel.add(new JButton("1"));
panel.add(new JButton("2"));
4. GridBagLayout
- Description: Flexible and powerful grid-based layout, allows varying cell sizes and alignment.
- Use: Advanced UIs requiring fine control over layout.
- Example:
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0; gbc.gridy = 0;
panel.add(new JButton("Button1"), gbc);
5. BoxLayout
- Description: Arranges components in a single row or column.
- Use: Vertical or horizontal stacking of components.
- Example:
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new JButton("Button1"));
6. CardLayout
- Description: Allows multiple components but only one is visible at a time like a stack of cards.
- Use: Wizard-style or tab-style interfaces.
- Example:
panel.setLayout(new CardLayout());
panel.add(new JPanel(), "Card1");
CardLayout cl = (CardLayout)(panel.getLayout());
cl.show(panel, "Card1");
7. GroupLayout
- Description: Used by GUI builders; aligns components hierarchically.
- Use: Useful in complex, form-based layouts.
- Example: Typically auto-generated by NetBeans IDE.
8. SpringLayout
- Description: Flexible layout where you define constraints (springs) between components.
- Use: Used where dynamic spacing is needed.
- Example:
SpringLayout layout = new SpringLayout();
panel.setLayout(layout);
layout.putConstraint(SpringLayout.WEST, b1, 5, SpringLayout.WEST, panel);
This guide provides a clear overview of each layout manager in Java Swing, along with where
and how they are used.