Skip to Content
Course content

211: Building a Simple JavaFX Application

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this happen a lot: a developer comes to me frustrated because their JavaFX app won't start, and when I look at their code, they've tried to instantiate a Stage directly inside the main method. They treat it like any other Java object—you call new Stage(), you set a title, and you call show(). It seems logical, right?

"I can just create a Stage wherever I want"

Here is what that broken approach looks like:

public class MyApp {
    public static void main(String[] args) {
        Stage stage = new Stage(); // This will throw an IllegalStateException
        stage.setTitle("My App");
        stage.show();
    }
}

If you run this, Java will scream at you with an IllegalStateException. Why? Because JavaFX isn't just a collection of classes; it's a toolkit that requires a specific runtime environment to be initialized before any UI components can exist. You can't just "new" a window into existence without the JavaFX platform being alive and kicking in the background.

The Application Lifecycle and the Stage-Scene Graph

To get a window on the screen, you have to play by the JavaFX rules. You don't call the UI logic in main; instead, you extend the Application class and override the start method. When you call launch(args) in your main method, JavaFX does the invisible work of spinning up the toolkit and then handing you a primary Stage via the start method.

Think of it as a theater production. The Stage is the actual window (the physical frame). The Scene is the current "set" or layout you're showing on that stage. Inside the scene, you have a "Scene Graph"—a tree of nodes like buttons, labels, and text fields. You can't have a scene without a stage, and you can't have a stage without a scene.

Building a Simple Tip Calculator

Let's build something slightly more useful than a blank window. We'll create a simple Tip Calculator. This will show you how to layout components and handle a basic event.

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

public class TipCalculator extends Application {

    @Override
    public void start(Stage primaryStage) {
        // 1. Create the UI components
        Label label = new Label("Enter Bill Amount:");
        TextField inputField = new TextField();
        Button calcButton = new Button("Calculate 20% Tip");
        Label resultLabel = new Label("Tip: $0.00");

        // 2. Define the behavior (Event Handling)
        calcButton.setOnAction(e -> {
            try {
                double bill = Double.parseDouble(inputField.getText());
                double tip = bill * 0.20;
                resultLabel.setText(String.format("Tip: $%.2f", tip));
            } catch (NumberFormatException ex) {
                resultLabel.setText("Please enter a valid number!");
            }
        });

        // 3. Arrange components in a layout (VBox stacks things vertically)
        VBox root = new VBox(10); // 10px spacing between elements
        root.getChildren().addAll(label, inputField, calcButton, resultLabel);

        // 4. Assemble the Stage and Scene
        Scene scene = new Scene(root, 300, 200);
        primaryStage.setTitle("QuickTip");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

I used a VBox here because it's the quickest way to get a vertical stack. In a real professional app, you'd likely use GridPane or FXML for more complex layouts, but for a simple tool, keep it lean. Notice how the setOnAction uses a lambda expression—this is the standard way to handle clicks in JavaFX. It's concise and keeps the logic right where the button is defined.




📋 Practical Task

Build a "Character Counter for Social Media" Application

Your task is to create a JavaFX application that helps a user keep track of how many characters they've typed, specifically for a platform like X (Twitter) which has a character limit.

  • Create a window titled "Post Length Checker".
  • Include a TextArea where the user can type their post.
  • Include a Label that updates in real-time (or via a button) to show the current character count.
  • Bonus: Make the label text turn red if the character count exceeds 280 characters.

Remember to extend Application and use the start method to initialize your UI components and scene.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.