Advance Java ProgrammingUnit 417 min read
Swing GUI Programming: Components, Layouts, Events & Design
Unit 4 of Advance Java Programming: Covers Java Swing’s GUI components (JFrame, JButtons, JLabels, etc.), layout managers (FlowLayout, GridLayout, BorderLayout), event handling (ActionListener, MouseListener), and practical GUI design principles with real-world examples and code implementations.
TAKEAWAYS:
- Learn how to create interactive GUI applications in Java using Swing components like
JFrame,JButton, andJTextField. - Understand layout managers (FlowLayout, GridLayout, BorderLayout) to position GUI elements dynamically.
- Master event handling using listeners (ActionListener, MouseListener) and adapter classes for cleaner code.
- Design 2D shapes and custom components using Swing’s graphics capabilities.
- Implement session tracking and database integration in GUI applications.
- Apply Swing in real-world apps like eSewa’s transaction forms or Pathao’s ride booking UI.
1. Introduction to Swing GUI Programming
Swing is a lightweight GUI widget toolkit for Java, built on top of Java’s Abstract Window Toolkit (AWT). It provides a platform-independent way to create desktop applications with buttons, text fields, menus, and more.
Key Swing Components
Swing components are reusable UI elements that extend JComponent. Below are the most commonly used ones:
| Component | Purpose | Example Use Case |
|---|---|---|
JFrame |
Top-level container (window) for the GUI. | Main window of an app. |
JButton |
Clickable button for actions. | "Submit" button in a form. |
JTextField |
Single-line text input field. | Username/password fields. |
JTextArea |
Multi-line text input/output area. | Order notes in Daraz. |
JLabel |
Displays text or an image. | "Enter your name:" prompt. |
JComboBox |
Dropdown list for selecting options. | Country dropdown in eSewa. |
JCheckBox |
Toggleable checkbox for options. | "Remember me" checkbox. |
JRadioButton |
Single-choice radio button group. | Payment method selection. |
JList |
Scrollable list of items. | Product catalog in Daraz. |
JTable |
Displays tabular data (rows and columns). | Bank transaction history. |
![]() |
|---|
| Common Swing components used in GUI applications. |
2. Creating a Basic GUI Application
To create a GUI, you need a top-level container (e.g., JFrame) and components inside it.
Example: Simple GUI with Input Fields
import javax.swing.*;
import java.awt.event.*;
```figure
{"type":"network","nodes":["JFrame","JLabel","JTextField","JButton","JPanel"],"edges":[["JFrame","JLabel","add"],["JFrame","JTextField","add"],["JFrame","JButton","add"],["JPanel","JLabel","add"],["JPanel","JTextField","add"]],"caption":"Example GUI layout with a JPanel grouping related components (label + text field)."}
public class SimpleGUI { public static void main(String[] args) { JFrame frame = new JFrame("Number Comparator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200);
// Components
JLabel label1 = new JLabel("Enter first number:");
JTextField tf1 = new JTextField(10);
JLabel label2 = new JLabel("Enter second number:");
JTextField tf2 = new JTextField(10);
JButton button = new JButton("Compare");
JLabel result = new JLabel("Result will appear here.");
// Layout (FlowLayout by default)
frame.add(label1);
frame.add(tf1);
frame.add(label2);
frame.add(tf2);
frame.add(button);
frame.add(result);
// Event handling
button.addActionListener(e -> {
int num1 = Integer.parseInt(tf1.getText());
int num2 = Integer.parseInt(tf2.getText());
if (num1 > num2) {
result.setText(num1 + " is greater than " + num2);
} else {
result.setText(num2 + " is greater than or equal to " + num1);
}
});
frame.setVisible(true);
}
}
State After Each Step
Initial Frame Creation
JFrame frame = new JFrame("Number Comparator");
A blank window with title "Number Comparator".Adding Components
frame.add(label1); frame.add(tf1); ... frame.add(result);
Labels, text fields, button, and result label appear in default FlowLayout.
- Event Handling (After Button Click)
button.addActionListener(e -> { ... });
Result label updates based on user input.
3. Layout Managers in Swing
Layout managers automatically arrange components in a container. Swing provides several built-in layouts:
| Layout Manager | Description | When to Use |
|---|---|---|
| FlowLayout | Arranges components left-to-right, top-to-bottom. | Simple forms with few components. |
| BorderLayout | Divides container into 5 regions (N/S/E/W/CENTER). | Main app windows. |
| GridLayout | Places components in a grid of equal-sized cells. | Tables or fixed-size forms. |
| GridBagLayout | Flexible grid with row/column spanning and alignment. | Complex layouts. |
| BoxLayout | Arranges components vertically or horizontally in a box. | Compact forms. |
Example: BorderLayout in Action
Code Example: BorderLayout Usage
JFrame frame = new JFrame("BorderLayout Example");
frame.setLayout(new BorderLayout());
JButton northBtn = new JButton("North");
JButton southBtn = new JButton("South");
JButton eastBtn = new JButton("East");
JButton westBtn = new JButton("West");
JButton centerBtn = new JButton("Center");
frame.add(northBtn, BorderLayout.NORTH);
frame.add(southBtn, BorderLayout.SOUTH);
frame.add(eastBtn, BorderLayout.EAST);
frame.add(westBtn, BorderLayout.WEST);
frame.add(centerBtn, BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setVisible(true);
State After Layout Application
+---------------------+
| [North] |
+---------------------+
| [West] [Center] [East]|
+---------------------+
| [South] |
+---------------------+
4. Event Handling in Swing
Events are user interactions (e.g., button clicks, mouse movements) that trigger actions. Swing uses listeners to handle events.
Common Event Listeners
| Listener | Triggered By | Example Method |
|---|---|---|
ActionListener |
Button clicks, form submissions. | actionPerformed(ActionEvent e) |
MouseListener |
Mouse clicks, drags, movements. | mouseClicked(MouseEvent e) |
KeyListener |
Keyboard key presses. | keyPressed(KeyEvent e) |
ItemListener |
Checkbox, radio button selections. | itemStateChanged(ItemEvent e) |
Example: MouseEvent Handling
JButton mouseBtn = new JButton("Click Me!");
mouseBtn.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
JOptionPane.showMessageDialog(null, "Double-clicked!");
}
}
});
Adapter Classes
Adapter classes reduce boilerplate code by providing empty method implementations. For example:
MouseAdapterextendsMouseListenerbut does nothing.- You override only the methods you need.
classDiagram
class MouseListener {
<<interface>>
+mouseClicked(MouseEvent)
+mousePressed(MouseEvent)
+mouseReleased(MouseEvent)
+mouseEntered(MouseEvent)
+mouseExited(MouseEvent)
}
class MouseAdapter {
+mouseClicked(MouseEvent) {}
+mousePressed(MouseEvent) {}
+mouseReleased(MouseEvent) {}
+mouseEntered(MouseEvent) {}
+mouseExited(MouseEvent) {}
}
MouseAdapter --> MouseListener : Implements
MouseAdapter : "Empty implementations"
MouseListener : "Full interface"Why Use Adapters?
| Without Adapter | With Adapter |
|---|---|
| Must implement all methods, even if unused. | Only override needed methods. |
| More verbose code. | Cleaner, concise code. |
5. Drawing 2D Shapes in Swing
Swing allows custom drawing using paintComponent() in a JPanel.
Example: Drawing a Rectangle and Circle
import javax.swing.*;
import java.awt.*;
public class ShapeDrawing extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// Draw a red rectangle
g2d.setColor(Color.RED);
g2d.fillRect(50, 50, 100, 80);
// Draw a blue circle
g2d.setColor(Color.BLUE);
g2d.fillOval(200, 50, 100, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame("2D Shapes");
frame.add(new ShapeDrawing());
frame.setSize(400, 200);
frame.setVisible(true);
}
}
State After Drawing
+---------------------+
| [Red Rectangle] [Blue Circle] |
+---------------------+
6. Real-World Applications of Swing
Swing is widely used in desktop applications and enterprise software. Here’s how:
1. eSewa’s Transaction Form
- Idea Used:
JTextField,JButton,JLabel, and event handling for form submissions. - How?
JTextFieldfor account number and amount.JButtonfor "Pay Now" action.ActionListenerprocesses the payment.
2. Pathao’s Ride Booking UI
- Idea Used:
JComboBoxfor pickup/drop locations,JSliderfor fare adjustment, and layout managers for responsive design. - How?
JComboBoxlets users select pickup/drop locations.GridLayoutarranges fields neatly.
3. Daraz’s Order Queue System
- Idea Used:
JListfor displaying pending orders and event handling for order processing. - How?
JListshows a list of orders.MouseListenerallows users to select and process orders.
Worked Example: Bank Loan Calculator (Real Scenario)
A bank’s loan calculator GUI uses:
JTextFieldfor loan amount, interest rate, and tenure.JButtonto compute EMI.- Formula:
$$
EMI = P \times \frac{r(1 + r)^n}{(1 + r)^n - 1}
$$
where:
- ( P ) = Principal loan amount,
- ( r ) = Monthly interest rate,
- ( n ) = Number of months.
Code Example:
JButton calculateBtn = new JButton("Calculate EMI");
calculateBtn.addActionListener(e -> {
double principal = Double.parseDouble(tfPrincipal.getText());
double rate = Double.parseDouble(tfRate.getText()) / 12 / 100;
int tenure = Integer.parseInt(tfTenure.getText());
double emi = principal * (rate * Math.pow(1 + rate, tenure)) /
(Math.pow(1 + rate, tenure) - 1);
tfEmi.setText(String.format("%.2f", emi));
});
Trace Table:
| Step | Action | tfPrincipal | tfRate | tfTenure | tfEmi (Result) |
|---|---|---|---|---|---|
| 1 | User enters 500,000 | 500000 | - | - | - |
| 2 | User enters 10% | 500000 | 10 | - | - |
| 3 | User enters 24 months | 500000 | 10 | 24 | - |
| 4 | Clicks "Calculate EMI" | 500000 | 10 | 24 | 22,241.41 |
7. Session Tracking in Swing
Session tracking keeps user-specific data (e.g., login status) between requests. Swing uses:
JOptionPanefor simple dialogs.JInternalFramefor multi-tab interfaces.JTable+DefaultTableModelfor dynamic data display.
Example: Login Session Tracking
public class LoginGUI {
private JFrame frame;
private JTextField usernameField;
private JPasswordField passwordField;
private boolean isLoggedIn = false;
public LoginGUI() {
frame = new JFrame("Login");
// ... (setup UI with username/password fields and login button)
JButton loginBtn = new JButton("Login");
loginBtn.addActionListener(e -> {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
if (username.equals("admin") && password.equals("123")) {
isLoggedIn = true;
JOptionPane.showMessageDialog(frame, "Login Successful!");
frame.dispose(); // Close login window
new DashboardGUI(username).setVisible(true);
} else {
JOptionPane.showMessageDialog(frame, "Invalid credentials!");
}
});
}
}
8. Exam Tips for Swing GUI Programming
Understand Layout Managers
- Always specify the layout manager when creating a container (e.g.,
frame.setLayout(new GridLayout(2, 3))). - Know when to use BorderLayout (main windows) vs. GridLayout (tables).
- Always specify the layout manager when creating a container (e.g.,
Event Handling Best Practices
- Use adapter classes (
MouseAdapter,ActionAdapter) to avoid implementing unused methods. - For complex events, use lambda expressions (as shown in examples).
- Use adapter classes (
Drawing Custom Shapes
- Override
paintComponent(Graphics g)in aJPanel. - Use
Graphics2Dfor advanced drawing (e.g., rounded rectangles, gradients).
- Override
Real-World Mapping
- Relate Swing components to apps you use daily (eSewa, Pathao, Daraz).
- Example: "How would you design a Pathao UI using Swing?"
Common Mistakes to Avoid
- Not setting
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)→ App hangs on close. - Ignoring layout managers → Components overlap or misalign.
- Hardcoding sizes → Use
pack()orsetSize()carefully.
- Not setting
Practical Question Patterns
- "Write a GUI to calculate the area of a circle using
JTextFieldandJButton." - "Design a login form with session tracking using
JOptionPane." - "Draw a rectangle and circle in Swing using
paintComponent()."
- "Write a GUI to calculate the area of a circle using
9. Summary Table: Key Swing Concepts
| Topic | Key Points | Example Use Case |
|---|---|---|
| JFrame | Top-level container for GUI. | Main window of an app. |
| Layout Managers | FlowLayout, BorderLayout, GridLayout for component arrangement. |
eSewa’s transaction form. |
| Event Handling | ActionListener, MouseListener, adapter classes for user interactions. |
Pathao’s ride selection. |
| 2D Shapes | paintComponent(Graphics g) for custom drawing. |
Daraz’s product preview. |
| Session Tracking | JOptionPane, JInternalFrame for user-specific data. |
Bank login system. |
| Database Integration | JTable + DefaultTableModel for dynamic data display. |
NEPSE stock market dashboard. |
┌───────────────────────────────────────────────────────┐
│ Swing GUI Programming │
├───────────────────┬───────────────────┬───────────────┤
│ Components │ Layout Managers │ Event │
│ (JFrame, JButton,│ (Flow, Border, │ Handling │
│ JTextField...) │ Grid, GridBag...) │ (Listener, │
└─────────┬─────────┴─────────┬─────────┴───────┬───────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Real-World Apps│ │ Exam Focus │ │ Common Mistakes│
│ (eSewa, Pathao)│ │ (Layouts, │ │ (No close op, │
└─────────────────┘ │ Events, Drawing)│ hardcoded sizes)│
└─────────────────┘ └─────────────────┘
Based on the TU BCA syllabus for Advance Java Programming (CACS354), unit 4.
Discussion
Loading…
