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

Swing Layout Managers (Part 1): Need, FlowLayout, BorderLayout & GridLayout

HIGH PRIORITY (Prep Guide)Official Syllabus + Supplementary~15 min study
Official KTU 2024 Syllabus Topics Covered Here
Introduction to layout managersNeed for layout managersFlowLayoutBorderLayoutGridLayout

1. Topic Introduction

What happens if you position buttons using hardcoded pixel coordinates (x=120, y=50) and a user resizes the window or switches from Windows to Linux with larger fonts? Components overlap or vanish off-screen! Java solves responsive UI positioning using Layout Managers—starting with the three everyday workhorses: FlowLayout, BorderLayout, and GridLayout.

2. Start From Zero: Word-Wrapped Text (Flow), 5-Zone Map (Border) & Chessboard Tiles (Grid)

1. **FlowLayout** works like words in a paragraph: components line up left-to-right and wrap nicely onto the next line when the row fills up (default for JPanel). 2. **BorderLayout** works like a 5-zone compass frame: Top (NORTH), Bottom (SOUTH), Left (WEST), Right (EAST), and a stretchy Middle (CENTER — default for JFrame's content pane!). 3. **GridLayout** works like a uniform spreadsheet or calculator keypad: EVERY cell gets forced to the exact same width and height!

Key Takeaway: Default layout of JPanel = FlowLayout. Default layout of JFrame = BorderLayout. GridLayout ignores preferred sizes and makes all cells identical rectangles.

3. Essential Exam Definitions

Layout Manager
An object implementing java.awt.LayoutManager assigned to a Container (setLayout(...)) that automatically computes positions and sizes of child components dynamically.
FlowLayout
Simple layout manager arranging components sequentially row by row in their preferred sizes, wrapping to new lines when horizontal space runs out.
BorderLayout
Layout manager dividing container space into five regions (NORTH, SOUTH, EAST, WEST, CENTER), allowing at most ONE component per region.
GridLayout
Layout manager dividing container space into an equal-sized rectangular grid of rows × cols cells.

4. Detailed Technical Explanation & Syntax

1. FlowLayout Constructors & Alignment

Constructors: FlowLayout() (center-aligned, 5px gaps), FlowLayout(int align) (FlowLayout.LEFT, CENTER, RIGHT, LEADING, TRAILING), FlowLayout(int align, int hgap, int vgap).

Respects each component's preferred size; ideal for toolbars and button rows inside a JPanel.

2. BorderLayout Regions & Stretching Behavior

Constructors: BorderLayout(), BorderLayout(int hgap, int vgap).

Adding components: frame.add(comp, BorderLayout.NORTH) (if omitted, defaults to CENTER!). Note: Adding a second component to the SAME region overwrites the first! NORTH/SOUTH stretch horizontally; EAST/WEST stretch vertically; CENTER absorbs all leftover height AND width!

3. GridLayout Behavior

Constructors: GridLayout(), GridLayout(int rows, int cols), GridLayout(int rows, int cols, int hgap, int vgap).

Components populate left-to-right, top-to-bottom. Passing 0 for rows (or cols) means 'as many rows (or columns) as needed' (new GridLayout(0, 3)).

5. Working Principle: Automatic Resizing via LayoutManager

  1. When frame.setVisible(true) runs or the user drags a window border, Swing calls layoutContainer(Container) on the assigned LayoutManager.
  2. Each manager queries component getPreferredSize() (for Flow/Border edges) or splits container dimensions evenly (GridLayout) and repositions widgets cleanly.

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

Combining `BorderLayout` (`JFrame`), `FlowLayout` (`JPanel`) & `GridLayout` (Keypad)BasicLayoutsDemo.java
Builds a realistic calculator-style frame combining all three foundational layout managers cleanly.
1import javax.swing.*;
2import java.awt.*;
3
4public class BasicLayoutsDemo extends JFrame {
5 public BasicLayoutsDemo() {
6 super("Flow, Border & Grid Layout Demo");
7 setLayout(new BorderLayout(8, 8)); // Default for JFrame, explicit gaps added
8
9 // NORTH: FlowLayout toolbar inside JPanel
10 JPanel topBar = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
11 topBar.add(new JLabel("Mode:"));
12 topBar.add(new JButton("Standard"));
13 topBar.add(new JButton("Scientific"));
14 add(topBar, BorderLayout.NORTH);
15
16 // CENTER: 2x3 GridLayout equal-sized button matrix
17 JPanel gridPanel = new JPanel(new GridLayout(2, 3, 6, 6));
18 for (int i = 1; i <= 6; i++) {
19 gridPanel.add(new JButton("Key " + i));
20 }
21 add(gridPanel, BorderLayout.CENTER);
22
23 // SOUTH: Status footer
24 add(new JLabel("Ready", SwingConstants.CENTER), BorderLayout.SOUTH);
25
26 setSize(380, 220);
27 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
28 }
29
30 public static void main(String[] args) {
31 if (GraphicsEnvironment.isHeadless()) {
32 System.out.println("BasicLayoutsDemo verified (Border + Flow + Grid).");
33 return;
34 }
35 SwingUtilities.invokeLater(() -> new BasicLayoutsDemo().setVisible(true));
36 }
37}
Expected Output
BasicLayoutsDemo verified (Border + Flow + Grid).
Keywords:FlowLayoutBorderLayoutGridLayoutJPanelsetLayout
Common Exam & Coding Mistakes
  • Adding two buttons to BorderLayout.NORTH directly (frame.add(b1, BorderLayout.NORTH); frame.add(b2, BorderLayout.NORTH);) — b2 replaces b1! Wrap them in a JPanel first.
  • Writing new GridLayout(0, 0) (at least one dimension must be positive!).

Real-World Applications

  • BorderLayout frames top toolbars (NORTH), sidebars (WEST), status bars (SOUTH), and main workspace (CENTER).
  • GridLayout structures calculator keypads and chessboards.

Important KTU Exam Points

  • Remember container defaults: JFrame content pane defaults to **BorderLayout**; JPanel defaults to **FlowLayout**!
  • Always draw clean schematic boxes showing the 5 Border regions, wrapped Flow blocks, and uniform Grid cells (Diagram 18).

Memory Techniques & Revision

  • Default Layouts: 'Frame = Border, Panel = Flow'.

Common Pitfalls to Avoid

  • Using setLayout(null) (absolute positioning) instead of Layout Managers—breaks completely across different screen resolutions and OS fonts.

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: Layout Managers automatically compute component sizes and positions dynamically so Swing GUIs adapt cleanly across OS fonts, screen DPIs, and window resizing.

  • FlowLayout (default for JPanel): Places components sequentially left-to-right at preferred size, wrapping onto subsequent rows (LEFT, CENTER, RIGHT).
  • BorderLayout (default for JFrame): Splits container into 5 zones (NORTH, SOUTH, EAST, WEST, CENTER); CENTER expands to fill remaining space; max 1 component per zone.
  • GridLayout: Divides container into equal-sized rectangular cells (rows × cols), forcing all components to identical dimensions.
Exam Diagram Note: Draw Flow, Border (5 labeled regions), and Grid schematics from Diagram 18.

Quick Understanding Check

1. If you add two buttons to BorderLayout.SOUTH directly on a JFrame, what happens?