CMP228 Advanced Programming with Java

Advanced Programming with JavaUnit 77 min read

GUI Programming: Swing & JavaFX Basics, Layouts, Events & Animations

Unit 7 of Advanced Programming with Java covers Swing and JavaFX frameworks for building graphical user interfaces (GUIs) in Java, including components, layouts, event handling, and animations, with practical examples and code traces.

TAKEAWAYS:

  • Swing vs. JavaFX: Swing is lightweight and built on AWT, while JavaFX is modern, hardware-accelerated, and supports CSS styling and multimedia.
  • Layout Managers: Use BorderLayout, GridLayout, FlowLayout, or GroupLayout to organize components dynamically.
  • Event Handling: Implement ActionListener, MouseListener, or lambda expressions to respond to user interactions.
  • Animations: Use Timeline and KeyFrame in JavaFX to create smooth transitions and effects.
  • Real-World Use: GUI frameworks power apps like eSewa’s payment interface (JavaFX for smooth animations) and Khalti’s dashboard (Swing for tabbed layouts).

1. Introduction to GUI Programming

Graphical User Interfaces (GUIs) allow users to interact with software visually. Java provides two frameworks:

  • Swing: Part of Java SE, lightweight, and built on AWT (Abstract Window Toolkit).
  • JavaFX: Modern, hardware-accelerated, and designed for rich media applications.

Swing vs. JavaFX: Comparison Table

Feature Swing JavaFX
Performance Software-rendered Hardware-accelerated (GPU)
Styling Limited (via UIManager) CSS-based styling
Multimedia Basic support Full support (video, audio)
Learning Curve Easier for beginners Steeper due to FXML/Scene Builder

2. Swing Basics

Swing provides reusable components like buttons, text fields, and panels. Key classes:

  • JFrame: Main window container.
  • JPanel: Holds other components.
  • JButton, JLabel, JTextField: Common UI elements.

Example: Simple Swing Window

import javax.swing.*;

public class SimpleSwingApp {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Hello Swing");
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton button = new JButton("Click Me!");
        frame.add(button);
        frame.setVisible(true);
    }
}

Visual Trace:

  1. JFrame is created with title "Hello Swing".
  2. JButton is added to the frame.
  3. setVisible(true) displays the window.

3. Layout Managers in Swing

Layout managers arrange components dynamically. Common ones:

  • BorderLayout: Divides space into 5 areas (NORTH, SOUTH, EAST, WEST, CENTER).
  • GridLayout: Arranges components in a grid.
  • FlowLayout: Places components left-to-right, top-to-bottom.

Example: BorderLayout Usage

JFrame frame = new JFrame("BorderLayout Demo");
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);

Visual:

graph TD
    A["BorderLayout Frame"] --> B["North"]
    A --> C["South"]
    A --> D["East"]
    A --> E["West"]
    A --> F["Center"]

4. Event Handling in Swing

Events (e.g., button clicks) are handled using listeners. Example:

button.addActionListener(e -> {
    JOptionPane.showMessageDialog(frame, "Button clicked!");
});

Trace:

  1. User clicks JButton.
  2. ActionEvent triggers ActionListener.
  3. JOptionPane displays a message.

5. JavaFX Basics

JavaFX uses a Scene Graph (nodes like Stage, Scene, Pane). Key classes:

  • Stage: Top-level window.
  • Scene: Container for nodes.
  • Button, Label, TextField: UI components.

Example: JavaFX Hello World

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class HelloJavaFX extends Application {
    @Override
    public void start(Stage stage) {
        Button btn = new Button("Click Me!");
        btn.setOnAction(e -> System.out.println("Hello JavaFX!"));

        StackPane root = new StackPane(btn);
        Scene scene = new Scene(root, 300, 200);
        stage.setScene(scene);
        stage.show();
    }
}

Visual Trace:

  1. Stage is created and configured.
  2. Button is added to a StackPane.
  3. Scene is set, and stage.show() displays the window.

6. Layouts in JavaFX

JavaFX uses Pane classes for layouts:

  • BorderPane: Similar to Swing’s BorderLayout.
  • GridPane: Grid-based layout.
  • HBox/VBox: Horizontal/vertical containers.

Example: GridPane Layout

GridPane grid = new GridPane();
grid.add(new Button("1"), 0, 0);
grid.add(new Button("2"), 1, 0);
grid.add(new Button("3"), 0, 1);

Visual:

graph TD
    A["GridPane"] --> B["Button 1 (0,0)"]
    A --> C["Button 2 (1,0)"]
    A --> D["Button 3 (0,1)"]

7. Animations in JavaFX

JavaFX supports animations via Timeline and KeyFrame. Example:

Timeline timeline = new Timeline(
    new KeyFrame(Duration.seconds(1), e -> {
        button.setTranslateX(button.getTranslateX() + 10);
    })
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();

Visual Trace:

stateDiagram-v2
    [*] --> Moving: Button moves right by 10px
    Moving --> Moving: Every 1 second

In the Real World

  1. eSewa’s Payment Interface
    • Uses JavaFX animations for smooth transitions between payment steps (e.g., sliding panels for card details).
  2. Khalti’s Dashboard
    • Employs Swing’s tabbed layout (JTabbedPane) to organize transactions, profiles, and settings.
  3. Nepal Stock Exchange (NEPSE) App
    • Leverages JavaFX charts (LineChart, BarChart) for real-time stock price visualization.

8. Worked Example: Bank ATM Simulation

Scenario: Simulate an ATM with a PIN input and balance check using Swing.

JFrame frame = new JFrame("ATM Simulation");
JTextField pinField = new JTextField(10);
JButton checkBalanceBtn = new JButton("Check Balance");

checkBalanceBtn.addActionListener(e -> {
    String pin = pinField.getText();
    if (pin.equals("1234")) {
        JOptionPane.showMessageDialog(frame, "Balance: NPR 50,000");
    } else {
        JOptionPane.showMessageDialog(frame, "Invalid PIN!");
    }
});

frame.add(pinField);
frame.add(checkBalanceBtn);
frame.setVisible(true);

Visual Trace:

  1. User enters PIN in JTextField.
  2. Clicks "Check Balance".
  3. If PIN is "1234", balance is displayed; else, error message appears.

Exam Tip

  • Swing: Focus on JFrame, JPanel, and layout managers. Remember setVisible(true) is required to display a window.
  • JavaFX: Know Stage, Scene, and Timeline for animations. Use setOnAction for event handling.
  • Common Mistakes:
    • Forgetting to call pack() or setSize() in Swing.
    • Not setting cycleCount in JavaFX animations (defaults to 1).
  • Practical Questions: Expect code snippets for GUI creation or event handling. Trace the flow of a simple animation or layout change.

Based on the PU BE Computer (PU) syllabus for Advanced Programming with Java (CMP228), unit 7.

Discussion

Loading…