FreeCode

Donate HTML/CSS JavaFX Java Home
JavaFX Starter Template JavaFX Labels JavaFX Buttons JavaFX Toggle Buttons JavaFX Radio Buttons and Toggle Groups JavaFX Checkboxes JavaFX Choice Boxes JavaFX Combo Boxes JavaFX Text Areas JavaFX Text Fields JavaFX List Views JavaFX Image Views JavaFX Color Pickers JavaFX Date Pickers JavaFX Resizable Split Pane Layouts JavaFX VBox (Vertical Box Layouts) JavaFX HBox (Horizontal Box Layouts) JavaFX Flow Pane Layouts JavaFX Tile Pane Layouts JavaFX Web Views

JavaFX Starter Template

Code Description:

The most basic and bare-bones JavaFX template needed to start any Java application with a UI. This includes all necessary components to set up a Scene and configure the window with a title.

Full JavaFX Starter Template Code:

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

public class Demo extends Application {

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

    @Override
    public void start(Stage primaryStage) throws Exception {
		
	VBox root = new VBox();
	Label label = new Label("Hello World");
		
	root.getChildren().add(label);
		
	primaryStage.setTitle("Window Title");
	primaryStage.setScene(new Scene(root, 700, 400));
	primaryStage.show();
		
    }

}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Note: You will NOT be able to copy and paste this code into your IDE unless you first set up JavaFX for your project. Check out this link if you need help setting up JavaFX:

JavaFX Comprehensive Setup Guide

Output:

JavaFX Starter Template Output Image

Code Notes:

  • Our "main" method contains "launch(args)" which launches the JavaFX "start" method.
  • The "start" method has one parameter, the primaryStage. The primaryStage is what controls the window of the application.
  • We create a new VBox called "root" and label called "label".
  • "root" is the main container for the scene and can be interchanged with other JavaFX layout components.
  • The "getChildren().add()" method allows us to add components to our main "root" component, in this case a label.
  • The primaryStage's title is set with the "setTitle" method. This is shown on the upper left of your application window.
  • The primaryStage's scene is set with the "setScene" method. A new scene is created with the root, the width, and the height of the window.
  • The primaryStage window is displayed with the "show" method.

Related Links:

JavaFX Comprehensive Setup Guide JavaFX Labels JavaFX Buttons JavaFX VBox (Vertical Box Layouts) JavaFX HBox (Horizontal Box Layouts)