Swing Layout Managers (Part 2): CardLayout, GridBagLayout & Complete Comparison
1. Topic Introduction
When simple flows, 5-zone borders, and uniform grids aren't flexible enough—such as building a multi-step wizard showing one panel at a time (CardLayout), or designing an asymmetric form where a text area spans 2 columns and stretches proportionally (GridBagLayout)—Swing offers two advanced layout managers.
CardLayout) vs Custom Spreadsheet Merged Cells (GridBagLayout)**CardLayout** stacks panels like a deck of cards—only ONE card shows on top at any moment, and clicking 'Next' flips to the next card (cardLayout.next(container) or cardLayout.show(container, "Step2")). **GridBagLayout** works like Excel where you can merge cells horizontally (gridwidth = 2), control how much extra space a column absorbs when resized (weightx), and anchor components inside cells (GridBagConstraints)!
CardLayout switches between overlapping panels cleanly (tabs/wizards). GridBagLayout + GridBagConstraints is Swing's most powerful (and detailed) grid layout allowing variable cell sizes and spans.3. Essential Exam Definitions
CardLayoutfirst, next, previous, last, show).GridBagLayout & GridBagConstraintsGridBagConstraints object (gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, anchor).4. Detailed Technical Explanation & Syntax
1. Using CardLayout
1. Keep a reference to CardLayout cards = new CardLayout(); and JPanel deck = new JPanel(cards);.
2. Add each child panel WITH a String identifier: deck.add(loginPanel, "LOGIN"); deck.add(dashPanel, "DASH");.
3. Switch cards anytime via cards.next(deck), cards.previous(deck), cards.first(deck), or cards.show(deck, "DASH").
2. Mastering GridBagLayout & GridBagConstraints
Unlike GridLayout (where every cell is identical), GridBagLayout reads rules from a GridBagConstraints instance passed during container.add(component, gbc):
gbc.gridx,gbc.gridy: 0-based column and row cell coordinates.gbc.gridwidth,gbc.gridheight: Number of columns/rows the component spans (e.g.,gridwidth = 2spans 2 columns).gbc.weightx,gbc.weighty: Proportion (0.0to1.0) determining how extra resize space is distributed.gbc.fill: Controls stretching inside its allocated cell (NONE,HORIZONTAL,VERTICAL,BOTH).gbc.insets: Paddingnew Insets(top, left, bottom, right)around the component.
5. Working Principle: How GridBagConstraints Places Widgets
- Create ONE reusable
GridBagConstraints gbc = new GridBagConstraints();. - Update
gbc.gridx,gbc.gridy,gbc.gridwidth,gbc.fillbefore eachpanel.add(comp, gbc)(GridBagLayoutclones the constraints internally per component!).
6. Examination-Ready Diagrams
Swing Layout Managers Visual Guide
Visual blueprint of all five syllabus Layout Managers (FlowLayout, BorderLayout, GridLayout, CardLayout, GridBagLayout) showing component arrangement rules.
- FlowLayout: Arranges left-to-right in rows, wrapping to next line when full (default for
JPanel). - BorderLayout: Divides container into 5 regions:
NORTH,SOUTH,EAST,WEST,CENTER(default forJFrame). - GridLayout: Uniform equal-sized rectangular grid of rows × columns.
- CardLayout: Stacks components like cards; only one card visible at a time.
- GridBagLayout: Flexible grid where components span multiple cells via
GridBagConstraints.
- Container delegates component sizing and positioning to its assigned
LayoutManager. - When frame resizes, LayoutManager automatically recalculates coordinates without hardcoded pixels.
- Draw 5 distinct wireframe boxes: Flow (inline blocks wrapping), Border (5 labeled compass regions), Grid (3×2 uniform matrix), Card (stacked overlapping panels), GridBag (varying cell spans with
gridx/gridy/gridwidth).
7. Complete Java Code Examples & Tracing
CardLayout plus a spanned form panel using GridBagLayout and GridBagConstraints.| 1 | import javax.swing.*; |
| 2 | import java.awt.*; |
| 3 | |
| 4 | public class AdvancedLayoutsDemo extends JFrame { |
| 5 | CardLayout cards = new CardLayout(); |
| 6 | JPanel deck = new JPanel(cards); |
| 7 | |
| 8 | public AdvancedLayoutsDemo() { |
| 9 | super("CardLayout & GridBagLayout Demo"); |
| 10 | setLayout(new BorderLayout()); |
| 11 | |
| 12 | // Card 1: GridBagLayout asymmetric form |
| 13 | JPanel formCard = new JPanel(new GridBagLayout()); |
| 14 | GridBagConstraints gbc = new GridBagConstraints(); |
| 15 | gbc.insets = new Insets(4, 4, 4, 4); |
| 16 | gbc.fill = GridBagConstraints.HORIZONTAL; |
| 17 | |
| 18 | gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 1; |
| 19 | formCard.add(new JLabel("Course:"), gbc); |
| 20 | |
| 21 | gbc.gridx = 1; gbc.gridy = 0; gbc.weightx = 1.0; |
| 22 | formCard.add(new JTextField("KTU OOP Java", 12), gbc); |
| 23 | |
| 24 | gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2; // Spans BOTH columns! |
| 25 | JButton nextBtn = new JButton("Go to Card 2"); |
| 26 | nextBtn.addActionListener(e -> cards.show(deck, "CARD2")); |
| 27 | formCard.add(nextBtn, gbc); |
| 28 | |
| 29 | // Card 2 |
| 30 | JPanel summaryCard = new JPanel(new FlowLayout()); |
| 31 | JButton backBtn = new JButton("Back to Form"); |
| 32 | backBtn.addActionListener(e -> cards.show(deck, "CARD1")); |
| 33 | summaryCard.add(new JLabel("Card 2: Ready for ESE!")); |
| 34 | summaryCard.add(backBtn); |
| 35 | |
| 36 | deck.add(formCard, "CARD1"); |
| 37 | deck.add(summaryCard, "CARD2"); |
| 38 | add(deck, BorderLayout.CENTER); |
| 39 | |
| 40 | setSize(380, 180); |
| 41 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
| 42 | } |
| 43 | |
| 44 | public static void main(String[] args) { |
| 45 | if (GraphicsEnvironment.isHeadless()) { |
| 46 | System.out.println("AdvancedLayoutsDemo (CardLayout + GridBagLayout) verified."); |
| 47 | return; |
| 48 | } |
| 49 | SwingUtilities.invokeLater(() -> new AdvancedLayoutsDemo().setVisible(true)); |
| 50 | } |
| 51 | } |
AdvancedLayoutsDemo (CardLayout + GridBagLayout) verified.
CardLayoutGridBagLayoutGridBagConstraintsgridxgridygridwidth- Forgetting to pass a string name when adding components to
CardLayout(deck.add(panel, "NAME")), makingcards.show()impossible. - Forgetting to reset
gbc.gridwidth = 1orweightx = 0when reusing the sameGridBagConstraintsobject for subsequent widgets!
Comparison Tables
| Layout Manager | Arrangement Style | Component Sizing | Typical Use Case |
|---|---|---|---|
FlowLayout | Sequential row-by-row wrap | Respects preferred size | Toolbars, button strips (JPanel default) |
BorderLayout | 5 zones (N, S, E, W, CENTER) | CENTER stretches both ways; edges stretch 1 axis | Main application windows (JFrame default) |
GridLayout | Uniform rows × cols matrix | Ignores preferred size; all cells identical | Calculators, uniform button grids |
CardLayout | Overlapping stack (1 visible) | Fills container size | Setup wizards, multi-view panels |
GridBagLayout | Dynamic cell grid + spans | Controlled via GridBagConstraints (fill, weight) | Complex responsive forms & dialogs |
Real-World Applications
- Installers/wizards use
CardLayout; complex form editors useGridBagLayout.
Important KTU Exam Points
- Memorize at least 5 fields of
GridBagConstraints:gridx,gridy,gridwidth,gridheight,weightx,fill,insets. - Be ready to reproduce the 5-way Layout Managers Comparison table for 6 marks!
Memory Techniques & Revision
- 5 Layouts — 'F-B-G-C-GB': Flow (line wrap), Border (5 compass), Grid (equal tiles), Card (stacked deck), GridBag (merged Excel cells).
Common Pitfalls to Avoid
- Confusing
GridLayout(equal uniform cells, no spanning) withGridBagLayout(flexible uneven spans viaGridBagConstraints).
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: Swing provides five core layout managers (FlowLayout, BorderLayout, GridLayout, CardLayout, GridBagLayout) balancing simplicity against layout precision.
FlowLayout: Wraps components row-wise in preferred sizes.BorderLayout: Five compass zones (NORTH,SOUTH,EAST,WEST,CENTER).GridLayout: Uniform equal-sized grid cells.CardLayout: Manages components as a stack of named cards, displaying only one card at a time (next(),previous(),show()), ideal for wizards.GridBagLayout: Most flexible grid manager usingGridBagConstraints(gridx,gridy,gridwidth,weightx,fill) to span multiple rows/columns asymmetrically.
Quick Understanding Check
1. Which layout manager lets a single button span across two columns inside a grid?