Advanced Java ProgrammingUnit 119 min read
Layout Managers & Event Handling: Swing/JavaFX, Listeners, Adapters
Unit 11 of Advanced Java Programming covers Java GUI layout managers (Flow, Grid, GridBag, Border, Box, HBox/VBox) and event handling models (delegation, listeners, adapters), with code examples for Swing/JavaFX and real-world applications like eSewa’s button layouts and Pathao’s dynamic UI updates.
Core Concepts
Layout Managers: Organizing GUI Components
Layout managers automatically position and resize GUI components (buttons, labels, etc.) when the window is resized. They eliminate manual pixel-based placement, making UIs responsive.
Types of Layout Managers
classDiagram
class LayoutManager {
<<abstract>>
+layoutContainer(Container parent)
}
class FlowLayout {
+FlowLayout()
+FlowLayout(int align)
+FlowLayout(int align, int hgap, int vgap)
}
class GridLayout {
+GridLayout(int rows, int cols)
+GridLayout(int rows, int cols, int hgap, int vgap)
}
class GridBagLayout {
+GridBagLayout()
+GridBagLayout(LayoutManager layout)
}
class BorderLayout {
+BorderLayout()
+BorderLayout(int hgap, int vgap)
}
class BoxLayout {
+BoxLayout(Container target, int axis)
}
class HBox {
+HBox()
+HBox(Node... children)
}
class VBox {
+VBox()
+VBox(Node... children)
}
LayoutManager <|-- FlowLayout
LayoutManager <|-- GridLayout
LayoutManager <|-- GridBagLayout
LayoutManager <|-- BorderLayout
LayoutManager <|-- BoxLayout
LayoutManager <|-- HBox
LayoutManager <|-- VBox1. FlowLayout (Swing)
- Behavior: Places components left-to-right, top-to-bottom like text in a paragraph.
- Constructors:
FlowLayout() // Center alignment, no gaps FlowLayout(int align) // LEFT, RIGHT, CENTER FlowLayout(int align, int hgap, int vgap) // Pixel gaps - Example: A row of buttons in eSewa’s payment options.
STATE AFTER ADDING BUTTONS:JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10)); panel.add(new JButton("Khalti")); panel.add(new JButton("eSewa")); panel.add(new JButton("Bank Transfer"));[Khalti][eSewa][Bank Transfer]
2. GridLayout (Swing)
- Behavior: Divides the container into a grid of equal-sized cells.
- Constructors:
GridLayout(int rows, int cols) // Fixed grid GridLayout(int rows, int cols, int hgap, int vgap) - Example: NTC’s tariff calculator grid (4x3 buttons for different plans).
STATE AFTER ADDING 12 BUTTONS:JPanel grid = new JPanel(new GridLayout(4, 3, 5, 5)); for (int i = 1; i <= 12; i++) grid.add(new JButton("Plan " + i));[P1][P2][P3][P4] [P5][P6][P7][P8] [P9][P10][P11][P12]
3. GridBagLayout (Swing)
- Behavior: Flexible grid where each component can span multiple cells with custom weights.
- Key Methods:
GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; // Position gbc.gridwidth = 2; // Span columns gbc.weightx = 1.0; // Stretch horizontally - Example: Daraz’s checkout form (dynamic fields for address, payment).
STATE AFTER ADDING LABEL + TEXTFIELD:GridBagLayout layout = new GridBagLayout(); container.setLayout(layout); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; container.add(new JLabel("Address:"), gbc); gbc.gridx = 1; container.add(new JTextField(), gbc);[Address:][____________]
4. BorderLayout (Swing)
- Behavior: Divides the container into 5 regions (NORTH, SOUTH, EAST, WEST, CENTER).
- Example: Pathao’s driver app (map in CENTER, buttons in NORTH/SOUTH).
JFrame frame = new JFrame(); frame.setLayout(new BorderLayout()); frame.add(new JButton("Start Ride"), BorderLayout.NORTH); frame.add(new JLabel("Map"), BorderLayout.CENTER);
5. HBox/VBox (JavaFX)
- Behavior: Horizontal/Vertical containers (like FlowLayout but with CSS-like styling).
- Example: YouTube’s video controls (play/pause in HBox).
HBox controls = new HBox(10); controls.getChildren().addAll(new Button("Play"), new Button("Pause"));
Event Handling: Responding to User Actions
Events are actions (clicks, keypresses) that trigger code execution. Java uses the delegation model (listeners) to handle events.
Event Delegation Model
- Source: Component (e.g.,
JButton). - Listener: Object that implements an interface (e.g.,
ActionListener). - Event Object: Passed to the listener (e.g.,
ActionEvent).
flowchart TD
A["User Clicks Button"] --> B["Event Object Created"]
B --> C["Listener's actionPerformed() Called"]
C --> D["Code Executes"]Types of Events
| Event Type | Interface | Example |
|---|---|---|
| Action Event | ActionListener |
Button clicks (JButton, JMenuItem) |
| Mouse Event | MouseListener |
Mouse clicks/drags |
| Key Event | KeyListener |
Keyboard presses |
| Focus Event | FocusListener |
Text field gains/loses focus |
| Item Event | ItemListener |
Checkbox toggles |
| Window Event | WindowListener |
Window close/minimize |
Listener Interfaces vs. Adapter Classes
| Feature | Listener Interface | Adapter Class |
|---|---|---|
| Methods | Multiple abstract methods | Concrete implementations (do-nothing) |
| Use Case | When you need all events | When you need only some events |
| Example | ActionListener |
MouseAdapter (override mouseClicked) |
Example: Handling a button click with ActionListener:
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Form submitted!");
}
});
Using Adapter Class (for mouse events):
JButton button = new JButton("Drag Me");
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Clicked at: " + e.getX() + ", " + e.getY());
}
});
In the Real World
eSewa’s Payment Buttons
- Uses FlowLayout to arrange payment options (Khalti, eSewa, Bank) horizontally.
- Event Handling:
ActionListenertriggers payment processing when a button is clicked.
Pathao’s Dynamic UI
- GridBagLayout adjusts the driver’s interface (map, buttons, passenger details) based on screen size.
- Mouse Events:
MouseListenerdetects swipes on the map to recalculate routes.
NTC’s Tariff Calculator
- GridLayout displays 12 plan buttons in a 4x3 grid.
- Item Events:
ItemListenerupdates the selected plan’s details in real-time.
Worked Example: Traffic Light Controller (Swing)
Task: Simulate a traffic light using Timer and ActionListener.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TrafficLight {
public static void main(String[] args) {
JFrame frame = new JFrame("Traffic Light");
frame.setLayout(new GridLayout(3, 1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Red, Yellow, Green lights
JButton red = new JButton("RED");
JButton yellow = new JButton("YELLOW");
JButton green = new JButton("GREEN");
frame.add(red); frame.add(yellow); frame.add(green);
// Timer to cycle lights every 3 seconds
Timer timer = new Timer(3000, new ActionListener() {
boolean redOn = true;
public void actionPerformed(ActionEvent e) {
red.setBackground(redOn ? Color.RED : Color.GRAY);
yellow.setBackground(redOn ? Color.GRAY : Color.YELLOW);
green.setBackground(redOn ? Color.GRAY : Color.GREEN);
redOn = !redOn;
}
});
timer.start();
frame.pack();
frame.setVisible(true);
}
}
STATE AFTER EACH TIMER TICK:
- Tick 1:
RED(red=RED, yellow=GRAY, green=GRAY) - Tick 2:
GREEN(red=GRAY, yellow=GRAY, green=GREEN) - Tick 3:
YELLOW(red=GRAY, yellow=YELLOW, green=GRAY)
Exam Tip
Layout Managers:
- FlowLayout = left-to-right, top-to-bottom (like text).
- GridLayout = fixed grid (equal-sized cells).
- GridBagLayout = flexible grid (use
GridBagConstraints). - BorderLayout = 5 regions (NORTH/SOUTH/EAST/WEST/CENTER).
- JavaFX:
HBox/VBoxare like FlowLayout but with CSS styling.
Event Handling:
- Delegation Model: Listeners are separate objects.
- Adapter Classes: Use when you only need some event methods (e.g.,
MouseAdapter). - Common Pitfalls:
- Forgetting to call
super()in adapter classes. - Not setting the layout manager (
setLayout()). - Using absolute positioning (avoid
nulllayout).
- Forgetting to call
Code Structure:
- Always declare
GridBagConstraintsasfinalif modified in loops. - Use
ActionListenerfor buttons,MouseListenerfor mouse interactions.
- Always declare
Visual Summary:
mindmap
root((Layout Managers))
Swing
FlowLayout
GridLayout
GridBagLayout
BorderLayout
JavaFX
HBox
VBox
Event Handling
Delegation Model
Listener Interfaces
Adapter Classes
Event Types
ActionEvent
MouseEvent
KeyEventBased on the TU BSc CSIT syllabus for Advanced Java Programming (CSC409), unit 11.
Discussion
Loading…