2 Graphical Interfaces

Graphical User Interfaces

JavaFX

JavaFX is a modern framework for building desktop applications with rich graphical user interfaces (GUIs) in Java. It provides a comprehensive set of graphics and media packages that enable developers to design, create, test, and deploy applications with sophisticated visual elements and interactivity.

Key features of JavaFX include:

  • Rich User Interface Components: Buttons, labels, text fields, tables, charts, and many other controls for building complex interfaces
  • Layout Containers: Flexible layouts like VBox, HBox, GridPane, StackPane, and BorderPane for organizing components.
  • FXML Support: XML-based markup language for defining user interfaces separately from application logic.
  • CSS Styling: Ability to style applications using CSS for consistent and customizable appearance.
  • Scene Graph: Hierarchical tree structure for managing and rendering visual elements.
  • Event Handling: Robust event system for responding to user interactions like clicks, mouse movements, and keyboard input.

JavaFX applications are structured around three core concepts:

  1. Stage: The top-level window that contains your application
  2. Scene: A container that holds all visual elements and can be switched to show different views
  3. Node: Any visual element (controls, layouts, shapes) that can be displayed in a scene

To use JavaFX in your projects, you will need to download the JavaFX SDK and configure your IDE to include the JavaFX libraries. The following sections provide setup instructions for different development environments.

Replace JAVAFX_PATH with the actual path of the JavaFX installation directory.

Visual Studio Code

Download JavaFX (opens in a new tab) and extract it locally to {JAVAFX_PATH} (/Users/user/javafx-sdk-25, for example) then perform the following:

  1. Import JavaFX’s components (all the *.jar files under lib) into your project as referenced libraries. This will update .vscode/settings.json:

    .vscode/settings.json
    {
      "java.project.sourcePaths": ["src"],
      "java.project.outputPath": "bin",
      "java.project.referencedLibraries": [
        "lib/**/*.jar",
        "{JAVAFX_PATH}/lib/**/*.jar"
      ]
    }
  2. Create .vscode/launch.json using the Run and Debug view, then update your configuration with the following settings:

    .vscode/launch.json
    {
      "version": "0.2.0",
      "configurations": [
        {
          "type": "java",
          "name": "Application",
          "request": "launch",
          "mainClass": "Main",
          "vmArgs": "--module-path {JAVAFX_PATH}/lib --add-modules javafx.controls,javafx.fxml --enable-native-access=javafx.graphics"
        }
      ]
    }
  3. Launch the newly created configuration by selecting it from the dropdown menu in the Run and Debug view then running it using Start Debugging (F5).

Eclipse

Download JavaFX (opens in a new tab) and extract it locally to {JAVAFX_PATH} (/Users/user/javafx-sdk-25, for example) then follow the Getting Started with JavaFX (opens in a new tab) guide from OpenJFX:

  1. Open the marketplace using HelpEclipse Marketplace then search for and install the e(fx)clipse (opens in a new tab) plugin. Agree to the license terms and wait—this will take a while—until you receive a message asking you to restart Eclipse to apply the update.
  2. Select SettingsJavaFX then specify the location of the JavaFX directory ({JAVAFX_PATH}) in JavaFX 11+ SDK.
  3. Select SettingsJavaBuild PathUser Libraries then click on New to create a new user library named JavaFX. Click on Add External JARs and select all the *.jar files under {JAVAFX_PATH}/lib and add them.
  4. Select ProjectPropertiesJava Build PathLibrariesModulepath then Add LibraryUser Library and select JavaFX.
  5. Select SettingsRun/DebugString Substitution and create a new variable FX_PATH with the value {JAVAFX_PATH}/lib.
  6. Select RunRun ConfigurationsJava ApplicationArguments, set VM Arguments to --module-path ${FX_PATH} --add-modules javafx.controls and uncheck Use the -XstartOnFirstThread argument when launching with SWT.

IntelliJ IDEA

Follow the Create a new JavaFX project (opens in a new tab) guide from JetBrains.

SceneBuilder

Download and install SceneBuilder (opens in a new tab) locally on your machine.

SceneBuilder is a visual layout tool that lets you design JavaFX application interfaces by dragging and dropping components. Instead of hand-coding FXML files, you can visually arrange UI elements, set their properties, and define event handlers through an intuitive interface. SceneBuilder generates FXML files that you save in your project directory, which can then be loaded by your JavaFX application using FXMLLoader. This approach separates your UI design from your application logic, making it easier to maintain and modify your interface without touching the controller code.

Samples

Basic

Main.java
import java.io.IOException;
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;
 
public class Main extends Application {
  private int count = 0;
 
  @Override
  public void start(Stage stage) throws IOException {
    StackPane root = new StackPane();
 
    Button btn = new Button();
    btn.setText("Click me!");
    btn.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent event) {
        System.out.println("Count: " + ++count);
      }
    });
    root.getChildren().add(btn);
 
    stage.setTitle("JavaFX");
    stage.setScene(new Scene(root, 300, 250));
    stage.show();
  }
 
  public static void main(String[] args) { launch(args); }
}

FXML

Main.java
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
 
public class Main extends Application {
  @Override
  public void start(Stage stage) throws IOException {
    Parent root = FXMLLoader.load(getClass().getResource("View.fxml"));
    stage.setScene(new Scene(root, 300, 250));
    stage.setTitle("JavaFX");
    stage.show();
  }
 
  public static void main(String[] args) { launch(args); }
}
Controller.java
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
 
public class Controller {
  private int count = 0;
 
  @FXML private Button button;
 
  @FXML
  void handleClick(ActionEvent event) {
    System.out.println("Count: " + ++count);
  }
}
View.fxml
<?xml version="1.0" encoding="UTF-8"?>
 
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.StackPane?>
 
 
<StackPane xmlns="http://javafx.com/javafx/25" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller">
   <children>
      <Button fx:id="button" mnemonicParsing="false" onAction="#handleClick" text="Button" />
   </children>
</StackPane>