利用Springboot来驱动开发桌面程序

简介: 利用Springboot来驱动开发桌面程序

众所周知,SpringBoot是一款强大的Javaweb开发程序,这得益于其构造了一个Spring容器,然后通过依赖注入和控制反转,维护起一套Java对象和实例的管理机制,方便开发者去使用。在web应用开发的应用中,Springboot在Java层应用非常广,同样的,也可以利用SpringBoot来编写桌面程序。

标准的JavaFx代码

JavaFx是java中比较新的桌面端应用程序开发框架,一般来说,简单的使用JavaFx编写一个桌面程序的代码如下:
下面是一个实现一个树形结构的javafx程序

package com.demo123567.desktop.auto_tools;

import com.demo123567.desktop.auto_tools.menu.FxUtils;
import com.demo123567.desktop.auto_tools.utils.DatetimeUtil;
import com.demo123567.desktop.auto_tools.utils.Json;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.jcraft.jsch.*;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldTreeCell;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.converter.DefaultStringConverter;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.*;

public class SftpExample extends Application {
   
   

    @Override
    public void start(Stage primaryStage) {
   
   
        // 创建根节点
        TreeItem<String> rootItem = new TreeItem<>("Root");

        // 创建TreeView
        TreeView<String> treeView = new TreeView<>(rootItem);

        // 创建一个按钮,用于动态添加节点
        Button addButton = new Button("Add Node");
        addButton.setOnAction(event -> {
   
   
            // 获取当前选定的节点
            TreeItem<String> selectedItem = treeView.getSelectionModel().getSelectedItem();

            // 创建一个新的子节点
            TreeItem<String> newItem = new TreeItem<>("New Node");

            // 将新节点添加到选定节点的子节点列表中
            selectedItem.getChildren().add(newItem);

            // 展开选定节点
            selectedItem.setExpanded(true);
        });

        // 创建编辑按钮,用于编辑选定节点的名称
        Button editButton = new Button("Edit Node");
        editButton.setOnAction(event -> {
   
   
            // 获取当前选定的节点
            TreeItem<String> selectedItem = treeView.getSelectionModel().getSelectedItem();

            // 如果没有选定节点,则返回
            if (selectedItem == null) {
   
   
                return;
            }

            // 创建一个对话框,用于输入新节点名称
            TextInputDialog dialog = new TextInputDialog(selectedItem.getValue());
            dialog.setTitle("Edit Node");
            dialog.setHeaderText(null);
            dialog.setContentText("Enter new node name:");

            // 显示对话框,等待用户输入
            Optional<String> result = dialog.showAndWait();

            // 如果用户输入了新名称,则将其保存到选定节点中
            result.ifPresent(name -> selectedItem.setValue(name));
        });

        // 设置单元格工厂,用于更新节点名称
        treeView.setCellFactory(TextFieldTreeCell.forTreeView());

        // 创建BorderPane,将TreeView和按钮添加到其中
        BorderPane root = new BorderPane();
        root.setCenter(treeView);

        // 创建VBox,将按钮添加到其中
        VBox buttonBox = new VBox();
        buttonBox.getChildren().addAll(addButton, editButton);
        root.setRight(buttonBox);

        // 创建场景
        Scene scene = new Scene(root, 300, 250);

        // 设置舞台标题并显示
        primaryStage.setTitle("TreeView Example");
        primaryStage.setScene(scene);
        primaryStage.show();

        // 添加监听器,在对话框关闭时输出JSON
        primaryStage.setOnCloseRequest(event -> {
   
   
            // 获取TreeView的根节点
            TreeItem<String> rootNode = treeView.getRoot();

            // 将根节点转换为Map
            Map<String,Object> ans = toMap(rootNode);

            // 输出JSON字符串
            System.out.println(Json.toJson(ans));
        });
    }
    private Map<String,Object> toMap(TreeItem<String> node) {
   
   
        Map<String,Object> ans = new HashMap<>();
        ans.put("name",node.getValue());
        if (node.getChildren().size() > 0) {
   
   
            List<Map<String,Object>> children = new ArrayList<>();
            for (TreeItem<String> child : node.getChildren()) {
   
   
                children.add(toMap(child));
            }
            ans.put("children", children);
        }

        return ans;
    }





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

运行的结构为
在这里插入图片描述

融合SpringBoot的JavaFx方法

可见,标准的启动方法为创建一个Main函数进行处理,那么我们可以联想到,如果使用Springboot,该如何启动,下面是一个完整的使用Springboot创建Javafx桌面应用的方法

springboot启动类

@SpringBootApplication
public class AutoToolsApplication {
   
   
    public static void main(String[] args) {
   
   
        Application.launch(MainApp.class, args);
    }
}

在Start函数中编写如下代码

    @Override
    public void start(Stage stage) throws Exception {
   
   
        // 创建 Spring 应用程序上下文
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册一个配置类,以便 Spring 能够扫描和识别所有的 Bean
        context.register(Config.class);
        context.register(RestTemplateConfig2.class);
//        context.register(ThreadPoolConfig.class);
        // 启动 Spring 应用程序上下文
        context.refresh();
        stage.setTitle("效率工具");
        HostServices hostServices = getHostServices();

        MenuService functionMenuService = SpringContextUtil.getBean(MenuService.class);
        MenuBar menuBar = new MenuBar(thingMenu(functionMenuService),
                chatMenu(functionMenuService),
                browserMenu(functionMenuService,hostServices),
                logMenu(functionMenuService),
                projectMenu(functionMenuService),
                knowledgeMenu(functionMenuService),
                scriptMenu(functionMenuService),
                toolsMenu(functionMenuService),
                buttMenu(functionMenuService),
                networkToolsButton(functionMenuService),
                reminderMenu(functionMenuService),
                configurationMenu(functionMenuService),
                loveMenu(functionMenuService),
                knowledgeTreeMenu(functionMenuService,hostServices),
                sidelineMenu(functionMenuService),
                dataMenu(functionMenuService)
        );

        // 创建一个用于显示时钟的标签
        Label clockLabel = new Label();
        clockLabel.setFont(Font.font("Arial", FontWeight.BOLD, 48));

        // 创建一个用于显示"慢"字的标签
        Label slowLabel = new Label("沉心、平和、稳扎稳打");
        slowLabel.setFont(Font.font("SimSun", FontWeight.BOLD, 48));
        slowLabel.setTextFill(new Color(0f, 0f, 0f, 1));
        slowLabel.setPrefWidth(800);
        slowLabel.setAlignment(Pos.CENTER);

        StackPane clockContainer = new StackPane();
        StackPane.setAlignment(clockLabel, Pos.CENTER);
        StackPane.setAlignment(slowLabel, Pos.TOP_CENTER);

        clockContainer.getChildren().addAll(slowLabel, clockLabel);

        BorderPane.setAlignment(clockContainer, Pos.CENTER);
        BorderPane.setMargin(clockContainer, new Insets(150));
        // 创建一个用于更新时钟的时间线程
        Thread clockThread = new Thread(() -> {
   
   
            while (true) {
   
   
                Platform.runLater(() -> {
   
   
                    // 获取当前时间并设置到标签上
                    LocalDateTime currentTime = LocalDateTime.now();
                    String formattedTime = currentTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
                    clockLabel.setText(formattedTime);
                });
                try {
   
   
                    // 等待1秒钟
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
   
   
                    e.printStackTrace();
                }
            }
        });
        clockThread.setDaemon(true);
        clockThread.start();

        BorderPane root = new BorderPane();
        root.setTop(menuBar);
        root.setCenter(clockContainer);
        Scene scene = new Scene(root, 1920 * 0.6, 1080 * 0.6);
        stage.setScene(scene);
        stage.show();
    }

简单梳理一下这段代码,首先,利用下面的代码,创建Springboot上下文,并注册两个配置,叫Config和RestTemplateConfig2

// 创建 Spring 应用程序上下文
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册一个配置类,以便 Spring 能够扫描和识别所有的 Bean
        context.register(Config.class);
        context.register(RestTemplateConfig2.class);
//        context.register(ThreadPoolConfig.class);
        // 启动 Spring 应用程序上下文
        context.refresh();

然后在Config Bean的代码中加入@ComponentScan注解,那么整个应用的所有Bean都将被扫描并被spring上下文管理起来

@Configuration
@ComponentScan
public class Config {
   
   
}

然后,在后面的代码中,我们只需要像编写后端代码一样,编写桌面端程序即可。不需要额外学习任何的库或者技术

目录
相关文章
|
10月前
|
XML 人工智能 Java
优化SpringBoot程序启动速度
本文介绍了三种优化SpringBoot启动速度的方法:1) 延迟初始化Bean,通过设置`spring.main.lazy-initialization`为true,将耗时操作延后执行;2) 创建扫描索引,利用`spring-context-indexer`生成@ComponentScan的索引文件,加速类扫描过程;3) 升级至最新版SpringBoot,享受官方性能优化成果。这些方法能显著提升程序编译与启动效率。
1958 0
|
12月前
|
前端开发 Java 关系型数据库
基于Java+Springboot+Vue开发的鲜花商城管理系统源码+运行
基于Java+Springboot+Vue开发的鲜花商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的鲜花商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。技术学习共同进步
719 7
|
人工智能 Java 数据库
飞算 JavaAI:革新电商订单系统 Spring Boot 微服务开发
在电商订单系统开发中,传统方式耗时约30天,需应对复杂代码、调试与测试。飞算JavaAI作为一款AI代码生成工具,专注于简化Spring Boot微服务开发。它能根据业务需求自动生成RESTful API、数据库交互及事务管理代码,将开发时间缩短至1小时,效率提升80%。通过减少样板代码编写,提供规范且准确的代码,飞算JavaAI显著降低了开发成本,为软件开发带来革新动力。
|
缓存 NoSQL Java
基于SpringBoot的Redis开发实战教程
Redis在Spring Boot中的应用非常广泛,其高性能和灵活性使其成为构建高效分布式系统的理想选择。通过深入理解本文的内容,您可以更好地利用Redis的特性,为应用程序提供高效的缓存和消息处理能力。
1290 79
|
11月前
|
供应链 JavaScript BI
ERP系统源码,基于SpringBoot+Vue+ElementUI+UniAPP开发
这是一款专为小微企业打造的 SaaS ERP 管理系统,基于 SpringBoot+Vue+ElementUI+UniAPP 技术栈开发,帮助企业轻松上云。系统覆盖进销存、采购、销售、生产、财务、品质、OA 办公及 CRM 等核心功能,业务流程清晰且操作简便。支持二次开发与商用,提供自定义界面、审批流配置及灵活报表设计,助力企业高效管理与数字化转型。
826 2
ERP系统源码,基于SpringBoot+Vue+ElementUI+UniAPP开发
|
10月前
|
Java API 微服务
Java 21 与 Spring Boot 3.2 微服务开发从入门到精通实操指南
《Java 21与Spring Boot 3.2微服务开发实践》摘要: 本文基于Java 21和Spring Boot 3.2最新特性,通过完整代码示例展示了微服务开发全流程。主要内容包括:1) 使用Spring Initializr初始化项目,集成Web、JPA、H2等组件;2) 配置虚拟线程支持高并发;3) 采用记录类优化DTO设计;4) 实现JPA Repository与Stream API数据访问;5) 服务层整合虚拟线程异步处理和结构化并发;6) 构建RESTful API并使用Springdoc生成文档。文中特别演示了虚拟线程配置(@Async)和StructuredTaskSco
1077 0
|
人工智能 自然语言处理 前端开发
20分钟上手DeepSeek开发:SpringBoot + Vue2快速构建AI对话系统
本文介绍如何使用Spring Boot3与Vue2快速构建基于DeepSeek的AI对话系统。系统具备实时流式交互、Markdown内容渲染、前端安全防护等功能,采用响应式架构提升性能。后端以Spring Boot为核心,结合WebFlux和Lombok开发;前端使用Vue2配合WebSocket实现双向通信,并通过DOMPurify保障安全性。项目支持中文语义优化,API延迟低,成本可控,适合个人及企业应用。跟随教程,轻松开启AI应用开发之旅!
|
Java 数据库连接
【YashanDB知识库】Springboot启动找不到崖山jdbc驱动的问题处理
本文来自YashanDB官网,主要解决SpringBoot应用启动时出现“找不到崖山JDBC驱动”的问题,尽管lib目录下已有yashandb-jdbc-1.6.9.jar文件。错误信息显示`java.lang.ClassNotFoundException: com.yashandb.jdbc.Driver`。解决方案为:通过`which java`等命令定位Java安装路径,将驱动jar包复制到JRE的`lib/ext`目录下,最后重启应用即可。
|
JavaScript 前端开发 Java
Idea启动SpringBoot程序报错:Veb server failed to start. Port 8082 was already in use;端口冲突的原理与解决方案
本文解决了Idea启动SpringBoot程序报错:Veb server failed to start. Port 8082 was already in use的问题,并通过介绍端口的使用原理和操作系统的端口管理机制,可以更有效地解决端口冲突问题,并确保Web服务器能够顺利启动和运行。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
监控 Java 应用服务中间件
SpringBoot是如何简化Spring开发的,以及SpringBoot的特性以及源码分析
Spring Boot 通过简化配置、自动配置和嵌入式服务器等特性,大大简化了 Spring 应用的开发过程。它通过提供一系列 `starter` 依赖和开箱即用的默认配置,使开发者能够更专注于业务逻辑而非繁琐的配置。Spring Boot 的自动配置机制和强大的 Actuator 功能进一步提升了开发效率和应用的可维护性。通过对其源码的分析,可以更深入地理解其内部工作机制,从而更好地利用其特性进行开发。
550 6

热门文章

最新文章