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
HyperlinkandChoiceBoxenable 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
EventHandleror lambda expressions tied to nodes viasetOnAction(). - 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:
A. Button and Hyperlink
- Button: Triggers actions via
setOnAction(). - Hyperlink: Styled text that acts like a button (supports
visitedpseudo-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:
- Event Sources: Nodes (
Button,TextField). - Event Types:
ActionEvent,KeyEvent,MouseEvent. - Handlers: Lambda expressions or
EventHandlerclasses.
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:
- Create a Stage: Main window container.
- Design the Scene: Root node + layout.
- Add Controls: Buttons, text fields, etc.
- Handle Events: Attach listeners.
- 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:
NullPointerException:
- Cause: Forgetting to set a node’s parent (e.g.,
scene.setRoot(null)). - Fix: Verify
SceneandStageinitialization.
- Cause: Forgetting to set a node’s parent (e.g.,
Event Not Firing:
- Cause: Incorrect event handler attachment.
- Fix: Use
setOnAction()oraddEventHandler().
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
Understand the Scene Graph:
- Questions often ask about node hierarchies. Draw the structure for given examples.
Layout Manager Examples:
- Be ready to write code for
HBox,VBox,FlowPane, andGridPanewith 3+ controls.
- Be ready to write code for
Event Handling:
- Know how to attach listeners to
Button,TextField, andChoiceBox. Use lambda expressions for brevity.
- Know how to attach listeners to
JavaFX vs. Swing:
- Compare rendering, styling, and threading models. Memorize the table above.
Practical Coding:
- Expect questions like:
- "Write a JavaFX app with a
ChoiceBoxthat changes aLabel’s text." - "Design a form using
GridPanefor user registration."
- "Write a JavaFX app with a
- Always:
- Declare
StageandScene. - Use proper layout managers.
- Handle events with
setOnAction().
- Declare
- Expect questions like:
Common Pitfalls:
- Forgetting
stage.show(). - Not wrapping UI updates in
Platform.runLater(). - Misplacing nodes in the scene graph (e.g., adding to
Sceneinstead of aPane).
- Forgetting
Styling Bonus:
- If asked about
Hyperlinkor CSS, mention-fx-*properties (e.g.,-fx-background-color).
- If asked about
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…