KTU OOP Java2024 Scheme • 60M ESE
MODULE 4/Section 4: Swing Layout Managers

Swing Layout Managers (Part 2): CardLayout, GridBagLayout & Complete Comparison

MEDIUM PRIORITY (Prep Guide)Official Syllabus + Supplementary~15 min study
Official KTU 2024 Syllabus Topics Covered Here
CardLayoutGridBagLayoutComparison of layout managersJava examples demonstrating their use

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.

2. Start From Zero: Deck of Flashcards (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)!

Key Takeaway: 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

CardLayout
Layout manager treating components inside a container as a stack of cards where only one named card is visible at a time (first, next, previous, last, show).
GridBagLayout & GridBagConstraints
Flexible grid layout manager where components occupy dynamic rectangular regions configured via a GridBagConstraints 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 = 2 spans 2 columns).
  • gbc.weightx, gbc.weighty: Proportion (0.0 to 1.0) determining how extra resize space is distributed.
  • gbc.fill: Controls stretching inside its allocated cell (NONE, HORIZONTAL, VERTICAL, BOTH).
  • gbc.insets: Padding new Insets(top, left, bottom, right) around the component.

5. Working Principle: How GridBagConstraints Places Widgets

  1. Create ONE reusable GridBagConstraints gbc = new GridBagConstraints();.
  2. Update gbc.gridx, gbc.gridy, gbc.gridwidth, gbc.fill before each panel.add(comp, gbc) (GridBagLayout clones the constraints internally per component!).

6. Examination-Ready Diagrams

Diagram 18

Swing Layout Managers Visual Guide

FlowLayoutLeft-to-right wrapBorderLayoutNORTHCENTERSOUTH5 regions (JFrame default)GridLayoutEqual-size cells (r × c)CardLayoutActive Card1 card visible at onceGridBagLayoutMulti-cell constraints

Visual blueprint of all five syllabus Layout Managers (FlowLayout, BorderLayout, GridLayout, CardLayout, GridBagLayout) showing component arrangement rules.

Key Components
  • 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 for JFrame).
  • 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.
Step-by-Step Flow
  1. Container delegates component sizing and positioning to its assigned LayoutManager.
  2. When frame resizes, LayoutManager automatically recalculates coordinates without hardcoded pixels.
How to Draw in KTU Exam
  • 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` & `GridBagLayout` Combined ExampleAdvancedLayoutsDemo.java
Constructs a multi-card wizard panel using CardLayout plus a spanned form panel using GridBagLayout and GridBagConstraints.
1import javax.swing.*;
2import java.awt.*;
3
4public 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}
Expected Output
AdvancedLayoutsDemo (CardLayout + GridBagLayout) verified.
Keywords:CardLayoutGridBagLayoutGridBagConstraintsgridxgridygridwidth
Common Exam & Coding Mistakes
  • Forgetting to pass a string name when adding components to CardLayout (deck.add(panel, "NAME")), making cards.show() impossible.
  • Forgetting to reset gbc.gridwidth = 1 or weightx = 0 when reusing the same GridBagConstraints object for subsequent widgets!

Comparison Tables

Comparison of All 5 Swing Layout Managers (KTU Exam Summary)
Layout ManagerArrangement StyleComponent SizingTypical Use Case
FlowLayoutSequential row-by-row wrapRespects preferred sizeToolbars, button strips (JPanel default)
BorderLayout5 zones (N, S, E, W, CENTER)CENTER stretches both ways; edges stretch 1 axisMain application windows (JFrame default)
GridLayoutUniform rows × cols matrixIgnores preferred size; all cells identicalCalculators, uniform button grids
CardLayoutOverlapping stack (1 visible)Fills container sizeSetup wizards, multi-view panels
GridBagLayoutDynamic cell grid + spansControlled via GridBagConstraints (fill, weight)Complex responsive forms & dialogs

Real-World Applications

  • Installers/wizards use CardLayout; complex form editors use GridBagLayout.

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) with GridBagLayout (flexible uneven spans via GridBagConstraints).

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 using GridBagConstraints (gridx, gridy, gridwidth, weightx, fill) to span multiple rows/columns asymmetrically.
Exam Diagram Note: Draw all 5 schematics from Diagram 18.

Quick Understanding Check

1. Which layout manager lets a single button span across two columns inside a grid?