Spring Boot Swing integration tutorial

In Spring Boot Swing integration tutorial, we are going to combine Spring Boot framework with Swing library.

Spring is a popular Java application framework and Spring Boot is an evolution of Spring which helps create stand-alone, production-grade Spring based applications easily.

Swing is the principal GUI toolkit for the Java programming language. Swing is completely written in Java.

$ tree
.
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── zetcode
    │               └── gui
    │                   └── SwingApp.java
    └── test
        └── java

This is the project structure of the Spring Boot application.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zetcode</groupId>
    <artifactId>SpringBootSwing</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>    
    
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>        

    </dependencies>    

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

This is the Maven build file. The spring-boot-starter is the core starter that includes auto-configuration support, logging, and YAML. The application is packaged into a JAR file.

SwingApp.java
package com.zetcode.gui;

import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class SwingApp extends JFrame {

    public SwingApp() {

        initUI();
    }

    private void initUI() {

        JButton quitButton = new JButton("Quit");

        quitButton.addActionListener((ActionEvent event) -> {
            System.exit(0);
        });

        createLayout(quitButton);

        setTitle("Quit button");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void createLayout(JComponent... arg) {

        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        gl.setAutoCreateContainerGaps(true);

        gl.setHorizontalGroup(gl.createSequentialGroup()
                .addComponent(arg[0])
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
                .addComponent(arg[0])
        );
    }

    public static void main(String[] args) {

        ConfigurableApplicationContext ctx = new SpringApplicationBuilder(SwingApp.class)
                .headless(false).run(args);

        EventQueue.invokeLater(() -> {
            SwingApp ex = ctx.getBean(SwingApp.class);
            ex.setVisible(true);
        });
    }
}

This simple Swing application has a JButton on the panel. Clicking on the button terminates the appication.

@SpringBootApplication
public class SwingApp extends JFrame {

The Swing application is decorated with the @SpringBootApplication annotation. The annotation enables Spring Boot services.

JButton quitButton = new JButton("Quit");

Here we create a button component. This constructor takes a string label as a parameter.

quitButton.addActionListener((ActionEvent event) -> {
    System.exit(0);
});

We plug an action listener to the button. The listener's actionPerformed() method will be called when we click on the button. The action terminates the application by calling the System.exit() method.

createLayout(quitButton);

The child components need to be placed into containers. We delegate the task to the createLayout() method.

GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);

We use the GroupLayout to do the application layout.

ConfigurableApplicationContext ctx = new SpringApplicationBuilder(SwingApp.class)
        .headless(false).run(args);

The Spring Boot application is created with the SpringApplicationBuilder. We turn off the headless mode, which is suitable for server applications.

EventQueue.invokeLater(() -> {
    SwingApp ex = ctx.getBean(SwingApp.class);
    ex.setVisible(true);
});

We retrieve the Swing appication bean from the application context. The invokeLater() method places the application on the Swing Event Queue. It is used to ensure that all UI updates are concurrency-safe. In other words, it is to prevent GUI from hanging in certain situations.

$ mvn spring-boot:run -q

We run the application. The -q Maven option turns off Maven messages.

In this tutorial, we have created a Swing appication with Spring Boot framework. You might also be interested in the related tutorials: Java Swing tutorial, Standalone Spring applications, Java tutorial.