CSC409 Advanced Java Programming

Advanced Java ProgrammingUnit 311 min read

JavaFX: Architecture, Layouts, Controls & Event Handling

Unit 3 of Advanced Java Programming covers JavaFX’s architecture, scene graph, layout managers (FlowPane, HBox, VBox, GridPane), core controls (Button, TextField, Label, ChoiceBox, Hyperlink), event handling, and styling. It contrasts JavaFX with Swing and demonstrates building interactive GUIs with real-world examples

TAKEAWAYS:

  • JavaFX uses a scene graph (hierarchical node structure) and FXML for declarative UI design, unlike Swing’s lightweight components.
  • Layout managers (HBox, VBox, GridPane) automatically arrange components; FlowPane wraps items horizontally/vertically.
  • Controls like Hyperlink and ChoiceBox enable interactive elements with CSS styling and event handlers.
  • JavaFX supports CSS styling and multimedia (audio/video) natively, while Swing relies on third-party libraries.
  • Event handling in JavaFX uses EventHandler or lambda expressions tied to nodes via setOnAction().
  • Debugging JavaFX requires checking the scene graph hierarchy and event dispatch thread for errors.

---

### **1. Introduction to JavaFX**
JavaFX is Oracle’s modern GUI framework for Java, designed to replace Swing and AWT. It leverages **hardware-accelerated graphics**, **CSS styling**, and **rich media support** (audio/video). Key features:
- **Scene Graph**: A tree of nodes (`Scene`, `Pane`, `Control`) that renders UI elements.
- **FXML**: XML-based declarative UI design (alternative to Java code).
- **Multithreading**: Uses **JavaFX Application Thread** (UI updates) and **Worker Threads** (background tasks).

**Comparison with Swing**
| Feature          | JavaFX                          | Swing                          |
|------------------|---------------------------------|--------------------------------|
| **Rendering**    | Hardware-accelerated (Prism)    | Software-rendered (AWT peers)  |
| **Styling**      | CSS support                     | Limited (UIManager properties) |
| **Media**        | Built-in (audio/video)          | Third-party (e.g., JMF)        |
| **Architecture** | Scene Graph                      | Component hierarchy            |
| **Performance**  | Faster animations                | Slower for complex UIs         |

---

### **2. JavaFX Architecture**
JavaFX follows a **scene graph** model where UI elements are nodes in a tree. The core components are:
1. **Stage**: Top-level container (window).
2. **Scene**: Holds the root node and manages input events.
3. **Pane**: Layout containers (`HBox`, `VBox`, `FlowPane`, `GridPane`).
4. **Controls**: Interactive elements (`Button`, `TextField`, `Label`).

**Mermaid Diagram: Scene Graph Structure**
```mermaid
classDiagram
    class Stage {
        +setScene(Scene)
        +show()
    }
    class Scene {
        +setRoot(Node)
        +setOnKeyPressed()
    }
    class Pane {
        <<abstract>>
        +getChildren()
    }
    class Control {
        <<abstract>>
        +setStyle(String)
        +setOnAction(EventHandler)
    }
    Stage "1" --> "1" Scene : contains
    Scene "1" --> "1" Pane : root
    Pane <|-- HBox
    Pane <|-- VBox
    Pane <|-- FlowPane
    Pane <|-- GridPane
    Control <|-- Button
    Control <|-- TextField
    Control <|-- Label

3. Layout Managers in JavaFX

JavaFX provides five primary layout panes to organize components:

A. FlowPane

  • Arranges nodes horizontally (default) or vertically.
  • Wraps items to the next line if space is insufficient.
  • Example: Toolbar with buttons.
FlowPane flowPane = new FlowPane(10, 10); // hgap, vgap
flowPane.getChildren().addAll(new Button("OK"), new Button("Cancel"));

B. HBox and VBox

  • HBox: Aligns children horizontally (left-to-right).
  • VBox: Aligns children vertically (top-to-bottom).
  • Example: Form fields (labels + text fields).
HBox hbox = new HBox(10, new Label("Name:"), new TextField());
VBox vbox = new VBox(5, hbox, new Button("Submit"));

C. GridPane

  • Organizes nodes in a grid (rows/columns).
  • Useful for forms with aligned labels/inputs.
  • Example: Login form with username/password fields.
GridPane grid = new GridPane();
grid.add(new Label("User:"), 0, 0);
grid.add(new TextField(), 1, 0);
grid.add(new Button("Login"), 1, 1);

D. BorderPane

  • Divides space into five regions (top, bottom, left, right, center).
  • Example: Dashboard with menu on the left.

E. TilePane

  • Arranges nodes in a grid with fixed tile size.
  • Example: Image gallery.

When to Use Which?

Layout Use Case Example
FlowPane Dynamic wrapping (e.g., tags) Social media hashtags
HBox/VBox Linear alignment Buttons in a toolbar
GridPane Tabular data (forms) Login/signup forms
BorderPane Multi-region layouts Dashboards
TilePane Uniform-sized items Photo grids

4. Core Controls and Styling

JavaFX provides 140+ controls (buttons, text fields, tables, charts). Key examples:

  • Button: Triggers actions via setOnAction().
  • Hyperlink: Styled text that acts like a button (supports visited pseudo-class).
Hyperlink link = new Hyperlink("Visit Oracle");
link.setOnAction(e -> {
    getHostServices().showDocument("https://oracle.com");
});
link.getStyleClass().add("hyperlink"); // CSS styling

B. TextField and TextArea

  • TextField: Single-line input.
  • TextArea: Multi-line input (supports scrolling).
TextField nameField = new TextField();
nameField.setPromptText("Enter your name");

C. ChoiceBox and ComboBox

  • ChoiceBox: Dropdown list (single selection).
  • ComboBox: Editable dropdown (supports custom items).
ChoiceBox<String> colors = new ChoiceBox<>();
colors.getItems().addAll("Red", "Green", "Blue");
colors.setValue("Red");

D. CSS Styling

JavaFX supports CSS 2.1 for styling controls. Example:

.button {
    -fx-background-color: #4CAF50;
    -fx-text-fill: white;
    -fx-font-size: 14px;
}
.button:hover {
    -fx-background-color: #45a049;
}

5. Event Handling

JavaFX uses event-driven programming with:

  1. Event Sources: Nodes (Button, TextField).
  2. Event Types: ActionEvent, KeyEvent, MouseEvent.
  3. Handlers: Lambda expressions or EventHandler classes.

Example: Button Click Event

Button button = new Button("Click Me");
button.setOnAction(event -> {
    System.out.println("Button clicked!");
    Label label = new Label("Action performed!");
    vbox.getChildren().add(label);
});

Common Event Types

Event Type Triggered By Example
ActionEvent Button clicks, menu items button.setOnAction()
KeyEvent Keyboard presses textField.setOnKeyPressed()
MouseEvent Mouse clicks/moves node.setOnMouseClicked()
ChangeEvent ComboBox selection changes choiceBox.valueProperty().addListener()

6. Building a JavaFX Application

Steps to create a JavaFX program:

  1. Create a Stage: Main window container.
  2. Design the Scene: Root node + layout.
  3. Add Controls: Buttons, text fields, etc.
  4. Handle Events: Attach listeners.
  5. Show the Stage: primaryStage.show().

Example: Sum/Difference Calculator

public class Calculator extends Application {
    @Override
    public void start(Stage stage) {
        // Input fields
        TextField num1 = new TextField();
        TextField num2 = new TextField();
        Label result = new Label();

        // Buttons
        Button sumBtn = new Button("Sum");
        Button diffBtn = new Button("Difference");

        // Layout
        VBox layout = new VBox(10, num1, num2, sumBtn, diffBtn, result);

        // Event handlers
        sumBtn.setOnAction(e -> {
            int a = Integer.parseInt(num1.getText());
            int b = Integer.parseInt(num2.getText());
            result.setText("Sum: " + (a + b));
        });

        diffBtn.setOnAction(e -> {
            int a = Integer.parseInt(num1.getText());
            int b = Integer.parseInt(num2.getText());
            result.setText("Difference: " + (a - b));
        });

        // Show stage
        Scene scene = new Scene(layout, 300, 200);
        stage.setScene(scene);
        stage.setTitle("Calculator");
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

7. JavaFX vs. Swing: Key Differences

Feature JavaFX Swing
Rendering Engine Prism (hardware-accelerated) AWT peers (software-rendered)
Styling CSS 2.1 support Limited (UIManager properties)
Media Support Built-in (audio/video) Third-party (e.g., JMF)
Threading Model JavaFX Application Thread Swing Event Dispatch Thread
FXML Support Yes (declarative UI) No
3D Graphics Built-in (JavaFX 3D) Third-party (e.g., Java3D)
Learning Curve Moderate (new concepts) Steeper (legacy APIs)

Why Choose JavaFX?

  • Modern: Supports CSS, animations, and multimedia.
  • Performance: Hardware-accelerated rendering.
  • Future-Proof: Actively maintained by Oracle.

8. Debugging JavaFX Applications

Common issues and fixes:

  1. NullPointerException:

    • Cause: Forgetting to set a node’s parent (e.g., scene.setRoot(null)).
    • Fix: Verify Scene and Stage initialization.
  2. Event Not Firing:

    • Cause: Incorrect event handler attachment.
    • Fix: Use setOnAction() or addEventHandler().
  3. Layout Not Updating:

    • Cause: Modifying UI from a non-UI thread.
    • Fix: Use Platform.runLater() for UI updates.

Example: Safe UI Update

Platform.runLater(() -> {
    label.setText("Updated from background thread!");
});

Exam Tip

  1. Understand the Scene Graph:

    • Questions often ask about node hierarchies. Draw the structure for given examples.
  2. Layout Manager Examples:

    • Be ready to write code for HBox, VBox, FlowPane, and GridPane with 3+ controls.
  3. Event Handling:

    • Know how to attach listeners to Button, TextField, and ChoiceBox. Use lambda expressions for brevity.
  4. JavaFX vs. Swing:

    • Compare rendering, styling, and threading models. Memorize the table above.
  5. Practical Coding:

    • Expect questions like:
      • "Write a JavaFX app with a ChoiceBox that changes a Label’s text."
      • "Design a form using GridPane for user registration."
    • Always:
      • Declare Stage and Scene.
      • Use proper layout managers.
      • Handle events with setOnAction().
  6. Common Pitfalls:

    • Forgetting stage.show().
    • Not wrapping UI updates in Platform.runLater().
    • Misplacing nodes in the scene graph (e.g., adding to Scene instead of a Pane).
  7. Styling Bonus:

    • If asked about Hyperlink or CSS, mention -fx-* properties (e.g., -fx-background-color).

Note: For past exam questions, focus on comparisons (JavaFX vs. Swing), layout examples, and event-driven programming. Always test your code with sample inputs!

Based on the TU BSc CSIT syllabus for Advanced Java Programming (CSC409), unit 3.

Discussion

Loading…