JavaFX Introduction
Getting started with modern Java desktop applications
🎨 What is JavaFX?
JavaFX is a modern Java platform for creating rich desktop applications with beautiful user interfaces. It provides powerful graphics, media, and web capabilities for building engaging cross-platform applications.
// Simple JavaFX Application
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class HelloJavaFX extends Application {
public void start(Stage stage) {
Label label = new Label("Hello JavaFX!");
Scene scene = new Scene(label, 300, 200);
stage.setScene(scene);
stage.setTitle("My First JavaFX App");
stage.show();
}
}
Output:
Hello JavaFX!
Key JavaFX Concepts
Stage
The main window of your application
Stage stage = new Stage();
stage.setTitle("My App");
Scene
Container for all UI elements
Scene scene = new Scene(root, 400, 300);
stage.setScene(scene);
Scene Graph
Tree structure of UI components
VBox root = new VBox();
root.getChildren().add(new Label("Hello"));
Controls
Interactive UI elements
Button btn = new Button("Click Me");
TextField input = new TextField();
🔹 JavaFX Application Structure
Every JavaFX application follows this basic structure:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class MyApp extends Application {
@Override
public void start(Stage primaryStage) {
// Create UI components
Button button = new Button("Say Hello");
VBox root = new VBox(button);
// Create scene and stage
Scene scene = new Scene(root, 300, 200);
primaryStage.setTitle("JavaFX App");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:
🔹 Setting Up JavaFX
To get started with JavaFX development:
Requirements:
- Java 8 or higher
- JavaFX SDK (separate download for Java 11+)
- IDE like IntelliJ IDEA or Eclipse
- Scene Builder (optional visual designer)
// Module-info.java (for Java 9+)
module myapp {
requires javafx.controls;
requires javafx.fxml;
exports com.mycompany.myapp;
}
🔹 Your First Interactive App
Let's create a simple interactive application:
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 ClickCounter extends Application {
private int count = 0;
@Override
public void start(Stage stage) {
Label label = new Label("Clicks: 0");
Button button = new Button("Click Me!");
button.setOnAction(e -> {
count++;
label.setText("Clicks: " + count);
});
VBox root = new VBox(10, label, button);
Scene scene = new Scene(root, 200, 150);
stage.setTitle("Click Counter");
stage.setScene(scene);
stage.show();
}
}
Output:
Clicks: 0