Morrison's JavaFX Pages:




You will want to download the program Hello.java to read this page. Make sure you butcher it, experiment it, and modify it in your explorations.

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;

import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class Hello extends Application
{
    int clickCount;
    public Hello()
    {
        super();
        clickCount = 0;
    }
    @Override
    public void start(Stage primary)
    {
        primary.setTitle("Hello, World");
        Group root = new Group();
        System.out.println(root);
        Scene scene = new Scene(root, 300,250);
        Circle circ = new Circle(40, 40, 30);
        Button b = new Button("Click me!!");
        b.setLayoutX(100);
        b.setLayoutY(80);
        b.setOnAction(e-> {
            clickCount++;
            b.setText("" + clickCount);
        });
        root.getChildren().add(b);
        root.getChildren().add(circ);
        primary.setScene(scene);
        primary.show();
            
    }
    public static void main(String[] args)
    {
        Application.launch(args);
    }
}

We will step through this in its entirety.

What is your frame of mind? We assume you are familiar with using Swing and AWT to program graphically. The Application is the outer skin for your app; it plays the same role that JFrame plays in Swing.

The Application class has one constructor, which is just the default constructor. Once the Application object is constructed, the init() method is called. This method, by default, does nothing. You can use it to help set up housekeeping in your app. This method runs in its own thread.

Our class has a state variable clickCount that keeps track of the number of times the button in the window has been clicked. It is initialized explicitly in the constructor.

The class has a main method that calls the static method Appliction.launch(). This method is called to get the application to run. It should remind you of the use of javax.swing.SwingUtilities.invokeLater() that runs an app's run method and which ensures order in the event queue.

What is a stage? A stage is a top-level container for an app within the Application framework. The Scene object behaves like a content pane.

The start method begins the JavaFX Application thread, which functions much like Swing's Event Dispatch Thread. The scene object can hold zero or more nodes, each of which represents a graphical object.

A Group holds a collection of graphical widgets. The getChildren() method exposes this list so you can add items to it. Notice that we add a Circle and a Button object to the root Group.

The root group is added to a scene and this scene is displayed on the screen.