BIT401 Advanced Java Programming

Advanced Java ProgrammingUnit 38 min read

JavaFX Layouts, UI Controls & Event Handling

Unit 3 of Advanced Java Programming covers JavaFX’s UI framework, including layouts (BorderPane, GridPane, VBox), controls (buttons, text fields), event handling (ActionEvent, KeyEvent), and styling with CSS. Learn to build interactive desktop applications with modular, responsive interfaces.

TAKEAWAYS:

  • JavaFX layouts organize UI components spatially (e.g., BorderPane for regions, GridPane for grids).
  • Controls like Button, TextField, and ComboBox enable user interaction.
  • Event handling uses listeners (e.g., ActionEvent for clicks) to respond dynamically.
  • CSS styling in JavaFX improves UI aesthetics without Java code.
  • Scene Builder (drag-and-drop tool) accelerates UI design.
  • Real-world apps (e.g., eSewa’s payment UI, Khalti’s transaction screens) rely on JavaFX for responsive layouts and event-driven workflows.

1. Introduction to JavaFX

JavaFX is a Java library for building rich, interactive desktop, mobile, and web applications using Java and XML. It replaces Swing and offers:

  • Hardware-accelerated graphics (scalable vector graphics).
  • CSS styling for UI themes.
  • Built-in controls (buttons, tables, charts).
  • Scene Builder for drag-and-drop UI design.

Why Use JavaFX?

Feature JavaFX Swing
Performance GPU-accelerated (faster) CPU-bound (slower)
Styling CSS support Limited (proprietary look)
Modern UI Supports animations, media Basic, outdated controls
Tooling Scene Builder (drag-and-drop) Manual coding only

2. JavaFX Layouts: Organizing UI Components

Layouts define how components (buttons, labels, etc.) are positioned. Three key layouts:

A. BorderPane

Divides the scene into 5 regions:

  • TOP, BOTTOM, LEFT, RIGHT, CENTER (default fills remaining space). Use case: Dashboards (e.g., NTC’s electricity bill UI with menu on left, content in center).
BorderPane root = new BorderPane();
Button topButton = new Button("Top");
root.setTop(topButton);

Visual: BorderPane Regions

B. GridPane

Arranges components in a grid (rows/columns). Use case: Forms (e.g., Khalti’s login screen with username/password fields aligned).

GridPane grid = new GridPane();
grid.add(new Label("Name:"), 0, 0);
grid.add(new TextField(), 1, 0);

Visual: GridPane Example

C. VBox/HBox

Stacks components vertically (VBox) or horizontally (HBox). Use case: Pathao’s ride details (driver info stacked vertically).

VBox vbox = new VBox();
vbox.getChildren().addAll(new Label("Driver:"), new Button("Call"));

3. JavaFX Controls: Interactive Elements

Controls enable user interaction. Key examples:

Control Purpose Example
Button Clickable action "Submit" in eSewa forms
TextField Single-line text input Username in Khalti login
ComboBox Dropdown list City selection in Daraz orders
TableView Data tables NEPSE stock watchlist
Slider Range selection Volume control in media players

Visual: ComboBox in Action

stateDiagram-v2
    [*] --> ComboBox: Open
    ComboBox --> Options: Display
    Options --> Selected: Click
    Selected --> [*]: Close
    note right of ComboBox: **Example: City selection in Daraz**
    note right of Selected: **Example: NEPSE stock watchlist**

4. Event Handling in JavaFX

Events trigger actions (e.g., button clicks). Steps:

  1. Register a listener to an event type (ActionEvent, KeyEvent).
  2. Handle the event in the listener’s handle() method.

Example: Button Click

Button button = new Button("Click Me");
button.setOnAction(event -> {
    System.out.println("Button clicked!");
});

Visual: Event Flow

sequenceDiagram
    User->>Button: Clicks
    Button->>Listener: Fires ActionEvent
    Listener->>System: Prints "Clicked!"

Worked Example: Daraz Order Queue Simulate a "Place Order" button that updates a Label showing order status:

Label statusLabel = new Label("Ready to order");
Button orderButton = new Button("Place Order");
orderButton.setOnAction(e -> {
    statusLabel.setText("Order #12345 placed!");
});

Trace:

Step Action statusLabel Text
1 Initial state "Ready to order"
2 Click "Place Order" "Order #12345 placed!"

5. Styling with CSS in JavaFX

JavaFX supports CSS for styling. Example:

Button button = new Button("Styled Button");
button.setStyle("-fx-background-color: #4CAF50; -fx-text-fill: white;");

Visual: CSS Styling

Real-World Tie-In: eSewa’s Green Buttons eSewa uses CSS to style buttons with:

.button {
    -fx-background-color: #0066cc;
    -fx-text-fill: white;
    -fx-font-weight: bold;
}

6. Scene Builder: Drag-and-Drop UI Design

Scene Builder (part of NetBeans/IntelliJ) lets you:

  • Drag controls onto a design view.
  • Adjust properties (layout, styling) in the property inspector.
  • Generate Java code automatically.

Visual: Scene Builder Workflow


7. Complete JavaFX Program Example

Task: Build a simple calculator with Button and Label.

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

public class Calculator extends Application {
    @Override
    public void start(Stage stage) {
        Label result = new Label("0");
        Button addButton = new Button("+");
        addButton.setOnAction(e -> result.setText("10")); // Simulate addition

        VBox layout = new VBox(result, addButton);
        Scene scene = new Scene(layout, 200, 100);
        stage.setScene(scene);
        stage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}

Visual: Calculator UI After Click


In the Real World

  1. eSewa’s Payment UI

    • Layout: Uses GridPane to align fields (user ID, amount) and BorderPane for the sidebar menu.
    • Event Handling: ActionEvent triggers payment processing when "Pay Now" is clicked.
  2. Khalti’s Transaction Screen

    • Controls: ComboBox for selecting bank, TextField for amount, Button for confirmation.
    • CSS: Buttons styled with -fx-background-color: #FF6B35 (Khalti orange).
  3. NTC’s Bill Payment Portal

    • TableView: Displays pending bills (customer ID, due date, amount).
    • Event: Clicking "Pay" updates the table via TableView.setItems().

Exam Tip

  1. Layouts: Memorize the 5 regions of BorderPane and grid structure of GridPane. Exams often ask to "describe three layouts"—prioritize these two + VBox.
  2. Event Handling: Know the three steps (register listener → event fires → handle action) and common events (ActionEvent, KeyEvent).
  3. CSS Styling: Be ready to write one line of CSS (e.g., -fx-background-color) for a button or label.
  4. Scene Builder: While not always tested, understand it’s used to generate FXML/Java code for UIs.
  5. Worked Examples: Always trace variable changes (like the Daraz order example) to show understanding of event-driven logic.

Common Pitfalls:

  • Forgetting to set the scene on a stage (stage.setScene(scene)).
  • Misplacing components in GridPane (rows/columns start at 0).
  • Not importing javafx packages (e.g., import javafx.scene.control.*;).

Key Formula/Code Snippets for Exam:

// Register a button click listener
button.setOnAction(e -> System.out.println("Clicked!"));

// Add a node to a layout
VBox vbox = new VBox();
vbox.getChildren().add(new Button("Test"));

// CSS styling
button.setStyle("-fx-font-size: 20px; -fx-background-color: blue;");

Based on the TU BIT syllabus for Advanced Java Programming (BIT401), unit 3.

Discussion

Loading…