JavaFX: Structure of a JavaFX application

This entry is part 3 of 55 in the series JavaFX

Using the example created by Netbeans, let’s look the structure of a JavaFX application.

The class that we have created here is called JavaFXApplication5, this is an extension of the main class javafx.application.Application.

JavaFX applications need a start() method but not the main() method. But for backward compatibility with Java Swing, we always include the main() method in the application.

The UI Interface of a FX application always contains a stage and scene.  The stage is the top-level or outermost container.  Inside the outermost container is the scene.

When we create a button, we are creating it in the scene.

Structure of A JavaFX App
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javafxapplication5;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 *
 * @author daryl
 */
public class JavaFXApplication5 extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

j3

Series Navigation<< JavaFX: Creating the first application
JavaFX: How The Button Is Created >>

Leave a comment

Leave a Reply