使用Spring Boot来运行Swing应用程序

这里将展示如何在Spring Boot中运行Swing应用程序的方法。

首先,主方法将如下所示。将Headless设置为false非常重要。

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloWorldApplication {

	public static void main(String[] args) {
		SpringApplication springApplication = new SpringApplication(HelloWorldApplication.class);
		springApplication.setHeadless(false);
		springApplication.run(args);
	}

}

然后,创建一个实现了ApplicationRunner接口的类,并在run方法中编写Swing应用程序。这个run方法成为了实际的入口点。

package com.example;

import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JLabel;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class HelloWorldApplicationRunner implements ApplicationRunner {

	@Override
	public void run(ApplicationArguments args) throws Exception {
		JFrame frame = new JFrame("Hello World App");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JLabel label = new JLabel("Hello World!!!");
		label.setFont(new Font(Font.SERIF, Font.BOLD, 100));
		frame.add(label);
		
		frame.pack();
		frame.setVisible(true);
	}

}

让我们来试试运行。使用以下命令,创建一个jar文件。

D:\pleiades\workspace\HelloWorld>mvnw.cmd clean package

执行已创建的jar文件。

D:\pleiades\workspace\HelloWorld>java -jar target\HelloWorld-0.0.1-SNAPSHOT.jar

然后,创建的Swing应用程序将启动。

image.png

环境信息1

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.2.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>HelloWorld</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>HelloWorld</name>
	<description>HelloWorld project for Spring Boot</description>
	<properties>
		<java.version>21</java.version>
	</properties>
	<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>

环境信息②

D:\pleiades\workspace\HelloWorld>javac -version
javac 21-beta

D:\pleiades\workspace\HelloWorld>java -version
openjdk version "21-beta" 2023-09-19
OpenJDK Runtime Environment Temurin-21+35-202309042131 (build 21-beta+35-ea)
OpenJDK 64-Bit Server VM Temurin-21+35-202309042131 (build 21-beta+35-ea, mixed mode, sharing)
广告
将在 10 秒后关闭
bannerAds