Integrating JavaFX with Spring Boot for Desktop Applications

Are you a Java developer who loves building desktop applications? If yes, then you must have come across JavaFX, a popular Java GUI library. It provides a robust set of UI controls and an easy-to-learn scripting language. Besides, JavaFX is lightweight and has a simple API that allows you to build desktop applications faster.

But wait, what about integrating JavaFX with the robust Spring Boot framework? Have you thought about that? If not, it's time you did! Spring Boot framework is an open-source Java framework used to build microservices, web applications, and other Java-based applications. With Spring Boot, you can quickly set up and run your application with very little configuration.

In this tutorial, you will learn how to integrate JavaFX with Spring Boot to create desktop applications that have a more robust and modular design. You will also learn how to:

Prerequisites

Before we dive into this tutorial, ensure you have the following:

Creating a Spring Boot starter project

The first step to integrating JavaFX with Spring Boot is to create a Spring Boot starter project. You can use the Spring Initializr web tool or create one from the IDE of your choice. In this tutorial, we will use Intellij IDEA.

To create a Spring Boot starter project:

  1. Open Intellij IDEA and select Create New Project on the welcome screen.

  2. Select Spring Initializr from the list of options and click Next.

  3. Configure the project settings as follows:

    • Group: javafx.tips

    • Artifact: javafx-spring-boot

    • Name: javafx-spring-boot

    • Description: Spring Boot and JavaFX integration

    • Package name: javafx.tips.javafx.spring.boot

    • Use Spring Boot Version: 2.5.5

    • Select the following dependencies:

      • Spring Web
      • Spring Boot DevTools
      • Spring Configuration Processor
    • Click Next.

  4. Configure the project location and click Finish.

Intellij IDEA will then generate the starter project with the selected dependencies.

Adding JavaFX to the Spring Boot Project

After creating the Spring Boot starter project, it's time to add JavaFX to the application.

To do this, add the following dependencies to the pom.xml file:

<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>16</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-graphics</artifactId>
    <version>16</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-fxml</artifactId>
    <version>16</version>
    <scope>compile</scope>
</dependency>

These dependencies allow you to use the most common JavaFX controls and to initialize your application from an FXML file.

Once you have added the above dependencies to your pom.xml file, make sure to build your project using mvn clean install.

Creating a Java Bean

After adding JavaFX dependencies to the project, it's time to create a Java Bean. This Java Bean will represent a form object in our application. It will carry the form data.

Create a new package com.javafx.tips.javafx.spring.boot.model, and inside the package, create a class named Form.

package javafx.tips.javafx.spring.boot.model;
public class Form {
    
    private String name;
    private String email;
    private String message;
    
    // Add getters and setters

}

Injecting the Java Bean into the Spring Boot Application Context

After creating the Java Bean, it's time to inject it into the Spring Boot application context. To do that, create a configuration file with the @Configuration annotation and include the Java Bean as a @Bean.

Create a new package, com.javafx.tips.javafx.spring.boot.config, and create the following class:

package javafx.tips.javafx.spring.boot.config;

import javafx.tips.javafx.spring.boot.model.Form;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    
    @Bean
    public Form form() {
        return new Form();
    }
    
}

The @Bean annotation creates a new instance of the Form class and places it in the application context. We can now use the Form object throughout the application.

Using Spring Boot to configure the JavaFX Application

Once you have created the Java Bean and injected it into the Spring Boot application context, it's time to use Spring Boot to configure the JavaFX application.

Create a new package, com.javafx.tips.javafx.spring.boot.controller, and create the following:

package com.javafx.tips.javafx.spring.boot.controller;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.tips.javafx.spring.boot.model.Form;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URL;
import java.util.ResourceBundle;

public class FormController implements Initializable {
    
    @FXML
    private TextField name;
    
    @FXML
    private TextField email;
    
    @FXML
    private TextField message;
    
    @Autowired
    private Form form;
    
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        name.textProperty().bindBidirectional(form.nameProperty());
        email.textProperty().bindBidirectional(form.emailProperty());
        message.textProperty().bindBidirectional(form.messageProperty());
    }

}

The JavaFX FormController is responsible for pre-populating the form fields with the values in the Form object. This is achieved by injecting the Form object using @Autowired annotation.

Creating the JavaFX User Interface

With the Java Bean and Spring Boot configured, we can now create the JavaFX user interface. We create a new package named com.javafx.tips.javafx.spring.boot.view, and inside this package, create the following FXML file named Form.fxml.

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.GridPane?>

<GridPane fx:controller="com.javafx.tips.javafx.spring.boot.controller.FormController"
          xmlns:fx="http://javafx.com/fxml"
          alignment="center"
          hgap="10"
          vgap="10">

    <Label GridPane.rowIndex="0" GridPane.columnIndex="0" text="Name:"/>
    <TextField fx:id="name" GridPane.rowIndex="0" GridPane.columnIndex="1"/>

    <Label GridPane.rowIndex="1" GridPane.columnIndex="0" text="Email:"/>
    <TextField fx:id="email" GridPane.rowIndex="1" GridPane.columnIndex="1"/>

    <Label GridPane.rowIndex="2" GridPane.columnIndex="0" text="Message:"/>
    <TextField fx:id="message" GridPane.rowIndex="2" GridPane.columnIndex="1"/>

</GridPane>

Bootstrapping the JavaFX Application

To bootstrap the JavaFX application, we create a new package named com.javafx.tips.javafx.spring.boot, and inside it, create the following class:

package com.javafx.tips.javafx.spring.boot;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.IOException;
import java.io.InputStream;

@SpringBootApplication
public class Main extends Application {
    
    private ConfigurableApplicationContext context;
    private Parent rootNode;
    
    /**
     * {@inheritDoc}
     */
    @Override
    public void init() {
        // Initializes the Spring Boot Application Context
        context = new SpringApplication(Main.class).run();
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setScene(new Scene(rootNode, 800, 600));
        primaryStage.show();
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public void stop() throws Exception {
        context.close();
    }
    
    /**
     * Entry point of the Application
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(Main.class, args);
    }
    
}

The Main class extends the Application class from the JavaFX library, and the @SpringBootApplication annotation causes the Spring Boot application to start automatically.

The init() method initializes the Spring Boot application context, and start() method sets the primary stage of the JavaFX application with the rootNode.

The stop() method is called when the application is destroyed, allowing us to clean up the resources and close the Spring Boot application context.

The main() method is the entry point of the JavaFX application, and it's launched using the launch() method.

Running the JavaFX application

Once the JavaFX application is configured and bootstrapped, we can run the JavaFX application by executing the JavaFX main class. To do this, right-click on the Main class in the project explorer and select Run.

After the application starts, the JavaFX form is displayed:

JavaFX Spring Boot Form

Packaging the JavaFX Application

With the JavaFX application running, it's time to package it. To package a JavaFX application using Spring Boot, you can use the Spring Boot Maven plugin. The plugin creates a runnable JAR file with all the required dependencies.

Add the following to the pom.xml file:

<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

After adding the plugin, build the application using mvn clean install.

The Maven build creates a runnable JAR file inside the target folder. You can run the JAR file using the command:

java -jar javafx-spring-boot-0.0.1-SNAPSHOT.jar

Conclusion

Integrating JavaFX with Spring Boot for desktop application development provides several benefits, including modular design and rapid development. In this tutorial, we have learned how to use Spring Boot with JavaFX, create the Java Bean, inject it into the Spring Boot application context, use Spring Boot to configure the JavaFX application, create the JavaFX user interface, bootstrap the JavaFX application, and package the JavaFX application using Spring Boot.

Leveraging the power of JavaFX and Spring Boot saves you time and effort and enables you to develop robust desktop applications faster. So, keep experimenting with JavaFX and Spring Boot for your next desktop application project!

Editor Recommended Sites

AI and Tech News
Best Online AI Courses
Classic Writing Analysis
Tears of the Kingdom Roleplay
ML Security:
Farmsim Games: The best highest rated farm sim games and similar game recommendations to the one you like
Local Meet-up Group App: Meetup alternative, local meetup groups in DFW
Nocode Services: No code and lowcode services in DFW
Graph Database Shacl: Graphdb rules and constraints for data quality assurance