2024.11.12

import okhttp3.*;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

public class TranslatorGUI {

public static final String API_KEY = "4M5FTgQ0RtALmrZVaezSyvbO";
public static final String SECRET_KEY = "GZMweUiQxzBifIO4QvadUgjNJqYMkONU";
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

public static void main(String[] args) {
// 创建并显示GUI
SwingUtilities.invokeLater(() -> new TranslatorGUI().createAndShowGUI());
}

// 创建图形界面
public void createAndShowGUI() {
// JFrame
JFrame frame = new JFrame("百度翻译工具");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null); // 窗口居中显示

// 主面板
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 1));

// 选择翻译方向
JPanel directionPanel = new JPanel();
JLabel directionLabel = new JLabel("请选择翻译方向:");
JRadioButton zhToEnButton = new JRadioButton("中文 -> 英文");
JRadioButton enToZhButton = new JRadioButton("英文 -> 中文");
ButtonGroup group = new ButtonGroup();
group.add(zhToEnButton);
group.add(enToZhButton);
directionPanel.add(directionLabel);
directionPanel.add(zhToEnButton);
directionPanel.add(enToZhButton);

// 输入框和按钮
JPanel inputPanel = new JPanel();
JTextField inputField = new JTextField(25);
JButton translateButton = new JButton("翻译");

// 显示翻译结果
JPanel outputPanel = new JPanel();
JTextArea outputArea = new JTextArea(5, 30);
outputArea.setEditable(false);

// 事件处理
translateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = inputField.getText();
if (text.isEmpty()) {
JOptionPane.showMessageDialog(frame, "请输入要翻译的文本!", "错误", JOptionPane.ERROR_MESSAGE);
return;
}

// 选择翻译方向
String from = "";
String to = "";

if (zhToEnButton.isSelected()) {
from = "zh";
to = "en";
} else if (enToZhButton.isSelected()) {
from = "en";
to = "zh";
} else {
JOptionPane.showMessageDialog(frame, "请选择翻译方向!", "错误", JOptionPane.ERROR_MESSAGE);
return;
}

// 调用翻译API并更新结果
try {
String translation = translate(text, from, to);
outputArea.setText(translation);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, "翻译失败,请稍后重试!", "错误", JOptionPane.ERROR_MESSAGE);
}
}
});

// 组件布局
panel.add(directionPanel);
panel.add(inputPanel);
inputPanel.add(inputField);
inputPanel.add(translateButton);
panel.add(outputPanel);
outputPanel.add(new JScrollPane(outputArea));

frame.add(panel);
frame.setVisible(true);
}

/**
* 从用户的AK,SK生成鉴权签名(Access Token)
*
* @return 鉴权签名(Access Token)
* @throws IOException IO异常
*/
static String getAccessToken() throws IOException {
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
+ "&client_secret=" + SECRET_KEY);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/oauth/2.0/token")
.method("POST", body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
return new JSONObject(response.body().string()).getString("access_token");
}

/**
* 使用百度翻译API进行翻译
*
* @param text 要翻译的文本
* @param from 源语言,例如 "zh" 表示中文,"en" 表示英文
* @param to 目标语言,例如 "zh" 表示中文,"en" 表示英文
* @return 翻译后的文本
* @throws IOException IO异常
*/
static String translate(String text, String from, String to) throws IOException {
MediaType mediaType = MediaType.parse("application/json");
String jsonRequest = String.format("{\"from\":\"%s\",\"to\":\"%s\",\"q\":\"%s\"}", from, to, text);
RequestBody body = RequestBody.create(mediaType, jsonRequest);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken())
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
String responseBody = response.body().string();

// 打印返回的响应内容,帮助调试
System.out.println("API Response: " + responseBody);

// 解析API返回的JSON结果,获取翻译后的文本
JSONObject jsonResponse = new JSONObject(responseBody);

// 获取 "result" 对象
JSONObject result = jsonResponse.getJSONObject("result");

// 获取 "trans_result" 数组
if (result.has("trans_result")) {
return result.getJSONArray("trans_result")
.getJSONObject(0)
.getString("dst"); // 获取翻译后的文本
} else {
// 如果没有 "trans_result",打印错误信息
System.out.println("Error: " + jsonResponse.toString());
return "翻译失败";
}
}
}
posted @   我也不想的  阅读(2)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示