JavaFX: How The Button Is Created

We look back at the same default example and see how the button is created and displayed in the scene of the interface.

There are basically 3 sequence of actions involved.

1. We first set up the button by putting the text “Click Me” inside the button.

btn.setText("Click Me");

2. We put the button inside a Stackpane by using Stackpane’s getChildren() and add() methods.


3.  We display the button in the scene.


This really shows why many of us took a long time to master Java Swing or Microsoft Foundation Class.  It is easy to be overwhelmed by these sequence of procedures that we need to set up just to display a button!

Take note that in the program below, I have made a slight modification to display a different button text when it is clicked.

 * 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 {

    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Click Me");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            public void handle(ActionEvent event) {

        StackPane root = new StackPane();

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");

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



Series Navigation<< JavaFX: Structure of a JavaFX application
JavaFX: Common classes >>