
人工智能的迅猛发展,基于大模型的技术已经渗透到各个行业。腾讯云推出的混元大模型在大模型领域中的表现可谓出色。同时,JavaFX 作为 Java 生态系统中功能强大的 UI 框架之一,凭借其丰富的组件和灵活的布局能力,逐渐成为构建桌面应用的首选工具。
本篇文章将详细讨论如何将 JavaFX 与混元大模型结合起来,构建一个智能化的桌面应用,用户可以通过该应用实时与混元大模型进行交互,实现类似智能对话的功能。我们将从技术选型、前后端集成、具体实现步骤等方面进行深入探讨。
先上结果:

JavaFX 是一个现代化的 UI 框架,允许开发者创建跨平台的桌面应用。与传统的 Swing 或 AWT 相比,JavaFX 提供了更强大的图形渲染能力、响应式布局设计,并支持使用 FXML 和 CSS 来定义界面结构与样式,使得 UI 开发更加灵活。
腾讯混元大模型是腾讯自主研发的通用大语言模型,具备强大的中文创作能力、复杂语境下的逻辑推理能力,以及可靠的任务执行能力。大模型采用了全新的DiT架构(Diffusion With Transformer),这是基于Transformer架构的扩散模型,混元大模型基于深度学习和大规模数据训练,具有强大的内容生成和理解能力。其技术原理包括深度学习、自然语言处理、注意力机制、知识图谱、大规模预训练、微调与优化等多个方面。
通过调用混元大模型的 API,开发者能够将自然语言处理能力无缝集成到自己的应用中,从而实现智能化的交互体验。

为了实现一个智能化的桌面应用,我们可以采用以下架构:
JavaFX 提供用户界面,允许用户输入文本消息,并展示与混元大模型的对话内容。前端通过 FXML 定义界面布局,使用 CSS 控制样式,确保用户体验流畅。
通过混元大模型 API 接收用户输入,生成符合语境的响应内容,并将结果返回给前端。
集成方式:
HttpClient 库调用混元大模型 API,进行异步请求处理。JavaFX 负责界面呈现,HttpClient 负责后端通信,最终实现前后端联动。在这里提一下,Java 8 中内置了JavaFX,但是从Java 9开始 JavaFX 不再包含在 JDK 中,而是作为一个独立的模块提供。
如果大家使用JDK 11 使用 Maven 或 Gradle 来管理项目,可以通过以下依赖导入 JavaFX
<dependencies>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>17.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-fxml</artifactId>
        <version>17.0.1</version>
    </dependency>
</dependencies>要使用腾讯云混元大模型,首先需要在腾讯云控制台获取 API Key 和 Secret。接下来,设置以下必要的参数:

HttpClient 进行网络请求,并解析返回的 JSON 数据。FXML 是 JavaFX 中用于定义 UI 布局的 XML 格式文件。我们可以使用 FXML 来构建一个基本的聊天界面,允许用户输入并发送消息。
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.*?>
<VBox xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1"
      fx:controller="com.demo.fx.controller.ChatController" spacing="10" stylesheets="/chat.css">
    <padding>
        <Insets top="10" right="10" bottom="10" left="10" />
    </padding>
    <children>
        <!-- 聊天消息显示区域 -->
        <ScrollPane fx:id="chatScrollPane" fitToWidth="true" VBox.vgrow="ALWAYS">
            <content>
                <VBox fx:id="chatBox" spacing="10" />
            </content>
        </ScrollPane>
        <!-- 用户输入区域 -->
        <HBox spacing="10">
            <TextField fx:id="userInput" HBox.hgrow="ALWAYS" onAction="#handleSendMessage" />
            <Button text="发送" onAction="#handleSendMessage" />
        </HBox>
    </children>
</VBox>控制器类是处理界面逻辑的地方。我们在 ChatController 中处理用户输入,并调用混元大模型 API 获取响应,之后将响应结果更新到 UI。
package com.demo.fx.controller;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.hunyuan.v20230901.models.ChatCompletionsResponse;
import com.tencentcloudapi.hunyuan.v20230901.models.Message;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
public class ChatController {
    // 共通参数
    private String secretId = "AKIDmuwoZ8YllZDj2EGBuRxGSccRAg4HGVfe";
    private String secretKey = "rVyJSN9qZFrJdomgT4aDj5GMPGtaHm3M";
    private String region = "ap-beijing";
    private String endpoint = "hunyuan.tencentcloudapi.com";
    private String model = "hunyuan-pro";
    @FXML
    private ScrollPane chatScrollPane;
    @FXML
    private VBox chatBox;
    @FXML
    private TextField userInput;
    // 处理发送消息的动作
    @FXML
    private void handleSendMessage() throws TencentCloudSDKException {
        String message = userInput.getText();
        if (!message.trim().isEmpty()) {
            addMessage("user", message); // 假设所有消息都是用户发送的
            userInput.clear(); // 清空输入框
            // 这里可以添加代码来处理AI的响应,并调用addMessage("ai", aiResponse);
            // 创建消息对象
            Message[] messages = new Message[1];
            Message content = new Message();
            content.setRole("user");
            content.setContent(message);
            messages[0] = content;
            // 调用混元大模型获取响应
            new Thread(() -> {
                try {
                    // 实例化服务类并发送请求
                    TencentCloudService service = new TencentCloudService();
                    ChatCompletionsResponse response = service.sendChatMessage(secretId, secretKey, region, endpoint, model, messages);
                    Label messageLabel = new Label(response.getChoices()[0].getMessage().getContent());
                    messageLabel.getStyleClass().addAll("message", response.getChoices()[0].getMessage().getRole() + "-message"); // 应用通用样式和特定发送者样式
                    // 更新UI必须在JavaFX应用主线程中进行
                    Platform.runLater(() -> chatBox.getChildren().add(messageLabel)); // 将消息添加到VBox容器中
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}为消息气泡增加样式,可以增强用户体验,提供清晰的视觉区分。
/* chat.css */
/* 设置整个VBox的背景颜色和内边距 */
.root {
    -fx-background-color: #f4f4f4;
    -fx-padding: 10;
}
/* 设置聊天消息显示区域的样式 */
#chatScrollPane {
    -fx-background-color: white;
    -fx-border-color: #cccccc;
    -fx-border-width: 1px;
}
/* 设置聊天消息区域的样式 */
#chatBox {
    -fx-background-color: white;
}
/* 设置用户输入区域的样式 */
#userInput {
    -fx-background-color: #ffffff;
    -fx-border-color: #cccccc;
    -fx-border-width: 1px;
    -fx-border-radius: 5px;
    -fx-padding: 5px;
}
/* 设置发送按钮的样式 */
#userInput > .button {
    -fx-background-color: #007acc;
    -fx-text-fill: white;
    -fx-border-radius: 5px;
    -fx-padding: 5px 10px;
}
/* 设置按钮悬停时的样式 */
#userInput > .button:hover {
    -fx-background-color: #005fa3;
}
/* 设置聊天消息显示区域的样式 */
#chatScrollPane {
    -fx-background-color: #f4f4f4; /* 浅灰色背景 */
    -fx-border-color: transparent; /* 透明边框 */
    -fx-border-width: 0;
    -fx-background-radius: 5px; /* 圆角 */
    -fx-padding: 10; /* 内边距 */
}
/* 设置聊天消息区域的样式 */
#chatBox {
    -fx-background-color: transparent; /* 透明背景 */
    -fx-spacing: 10; /* 消息之间的间距 */
}
/* 设置单条消息的样式 */
.message {
    -fx-background-color: white; /* 消息背景色 */
    -fx-border-color: #e0e0e0; /* 边框颜色 */
    -fx-border-width: 1px; /* 边框宽度 */
    -fx-border-radius: 10px; /* 圆角 */
    -fx-padding: 10; /* 内边距 */
/*    -fx-max-width: 60%; *//* 最大宽度 */
    -fx-alignment: top-left; /* 文本对齐方式 */
}
/* 设置用户发送的消息样式 */
.user-message {
    -fx-background-color: #dcf8c6; /* 用户消息背景色 */
    -fx-border-color: #a9d58e; /* 用户消息边框颜色 */
    -fx-alignment: top-right; /* 用户消息文本对齐方式 */
}
/* 设置AI发送的消息样式 */
.ai-message {
    -fx-background-color: #e6f7ff; /* AI消息背景色 */
    -fx-border-color: #b3d1ff; /* AI消息边框颜色 */
    -fx-alignment: top-left; /* AI消息文本对齐方式 */
}
/* 设置单条消息的通用样式 */
.message {
    -fx-font-family: 'Arial', sans-serif; /* 字体 */
    -fx-font-size: 14px; /* 字体大小 */
    -fx-text-fill: #333333; /* 文本颜色 */
    -fx-background-color: #ffffff; /* 消息背景色 */
    -fx-border-color: #e0e0e0; /* 边框颜色 */
    -fx-border-width: 1px; /* 边框宽度 */
    -fx-border-radius: 10px; /* 圆角 */
    -fx-padding: 10; /* 内边距 */
/*    -fx-max-width: 60%; *//* 最大宽度 */
    -fx-alignment: top-left; /* 文本对齐方式 */
}
/* 设置用户发送的消息样式 */
.user-message {
    -fx-background-color: #dcf8c6; /* 用户消息背景色 */
    -fx-border-color: #a9d58e; /* 用户消息边框颜色 */
    -fx-alignment: top-right; /* 用户消息文本对齐方式 */
}
/* 设置AI发送的消息样式 */
.ai-message {
    -fx-background-color: #e6f7ff; /* AI消息背景色 */
    -fx-border-color: #b3d1ff; /* AI消息边框颜色 */
    -fx-alignment: top-left; /* AI消息文本对齐方式 */
}看下运行效果:

为了与混元大模型交互,需要使用腾讯云提供的 HunyuanClient SDK 或者直接通过 HTTP API 请求。我们可以使用 Java 的 HttpClient 来实现与混元大模型的通信。

下面是一个简单的通过 HTTP 请求调用混元大模型的示例。可以使用此代码将用户输入发送到混元大模型,并接收智能回应:
package com.demo.fx.controller;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.SSEResponseModel;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.hunyuan.v20230901.HunyuanClient;
import com.tencentcloudapi.hunyuan.v20230901.models.ChatCompletionsRequest;
import com.tencentcloudapi.hunyuan.v20230901.models.ChatCompletionsResponse;
import com.tencentcloudapi.hunyuan.v20230901.models.Message;
public class TencentCloudService {
    // 封装共通参数创建逻辑
    private HunyuanClient createClient(String secretId, String secretKey, String region, String endpoint) {
        Credential cred = new Credential(secretId, secretKey);
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(endpoint);
        
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        
        return new HunyuanClient(cred, region, clientProfile);
    }
    // 封装聊天请求逻辑
    public ChatCompletionsResponse sendChatMessage(String secretId, String secretKey, String region, 
                                                   String endpoint, String model, Message[] messages) throws TencentCloudSDKException {
        HunyuanClient client = createClient(secretId, secretKey, region, endpoint);
        ChatCompletionsRequest req = new ChatCompletionsRequest();
        req.setModel(model);
        req.setMessages(messages);
        return client.ChatCompletions(req);
    }
    // 处理响应逻辑
    public void handleResponse(ChatCompletionsResponse resp) {
        if (resp.isStream()) { // 流式响应
            for (SSEResponseModel.SSE e : resp) {
                System.out.println(e.Data);
            }
        } else { // 非流式响应
            System.out.println(AbstractModel.toJsonString(resp));
        }
    }
}通过调用混元大模型 API,将收到一段包含模型生成文本的响应。为了将这一响应显示到 JavaFX 界面中,需要将返回的文本解析并格式化为消息气泡。
在桌面应用程序中,保持用户界面的流畅性是至关重要的。当调用混元大模型时,可能会遇到网络延迟或响应时间较长的问题。如果直接在 UI 线程中进行网络请求,将会导致界面卡顿,影响用户体验。因此,必须使用异步处理来避免阻塞主线程。
下面,我们通过创建一个新的线程来执行与大模型的通信操作。然后使用 Platform.runLater() 方法在网络请求完成后更新 UI 界面。这样,UI 线程可以始终保持响应,不会因为等待网络响应而卡顿。
// 调用混元大模型获取响应
new Thread(() -> {
    try {
        // 实例化服务类并发送请求
        TencentCloudService service = new TencentCloudService();
        ChatCompletionsResponse response = service.sendChatMessage(secretId, secretKey, region, endpoint, model, messages);
        Label messageLabel = new Label(response.getChoices()[0].getMessage().getContent());
        messageLabel.getStyleClass().addAll("message", response.getChoices()[0].getMessage().getRole() + "-message"); // 应用通用样式和特定发送者样式
        // 更新UI必须在JavaFX应用主线程中进行
        Platform.runLater(() -> chatBox.getChildren().add(messageLabel)); // 将消息添加到VBox容器中
    } catch (Exception e) {
        e.printStackTrace();
    }
}).start();
打开 Artifacts 设置:进入 File -> Project Structure -> Artifacts。
添加新的 Artifact:
+ 按钮,选择 JAR -> From modules with dependencies。main 方法的类)。配置输出目录和文件名:
Output directory 中选择输出目录。Archive name 中设置 JAR 文件的名称。
Build -> Build Artifacts。Build。
构建完成后,检查指定的输出目录,你应该能看到生成的 exe 文件。

最后,我们来看一下运行结果吧,现在谁有能说Java已死,大模型才是未来呢。

伴随着 AI 模型的进一步发展以及桌面应用的需求增长,JavaFX 与混元大模型的结合将有着更广阔的应用前景。从智能化交互到自动化操作,未来的桌面应用将更加智能化、多样化,满足用户日益增长的需求。
将 JavaFX 与混元大模型结合,不仅能够为用户提供更智能、更高效的交互体验,还能显著提升桌面应用的功能与扩展性。在未来,更多智能应用场景的实现将离不开这样的技术组合。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。