今天搞了百度翻译
package org.example;标签:String,每日,博客,34,import,new,frame,panel From: https://www.cnblogs.com/zzfdbk/p/17866209.html
import okhttp3.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import okhttp3.*;
import org.apache.hbase.thirdparty.com.google.gson.Gson;
import org.apache.hbase.thirdparty.com.google.gson.JsonArray;
import org.apache.hbase.thirdparty.com.google.gson.JsonObject;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class TranslationApp {
public static final String API_KEY = "cwk7TA68XaoxlS8ZhR4xijsZ";
public static final String SECRET_KEY = "mOXnsemPGalF6VVGIXmeSPu43o8P27Hu";
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
private JFrame frame;
private JTextField inputTextField;
private JComboBox<String> fromLanguageComboBox;
private JComboBox<String> toLanguageComboBox;
private JLabel outputLabel;
public TranslationApp() {
// 创建主窗口
frame = new JFrame("Translation App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
// 创建面板
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(10, 10)); // 设置边界布局,并添加间距
// 创建文本框和标签
inputTextField = new JTextField();
JButton translateButton = new JButton("Translate");
outputLabel = new JLabel("Translation will appear here.");
outputLabel.setForeground(new Color(34, 139, 34)); // 设置标签文本颜色为绿色
// 创建语言选择下拉框
String[] languages = {"en", "zh"};
fromLanguageComboBox = new JComboBox<>(languages);
toLanguageComboBox = new JComboBox<>(languages);
// 设置按钮的点击事件
translateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String inputText = inputTextField.getText();
String fromLanguage = (String) fromLanguageComboBox.getSelectedItem();
String toLanguage = (String) toLanguageComboBox.getSelectedItem();
String translatedText = translateText(inputText, fromLanguage, toLanguage);
MediaType mediaType = MediaType.parse("application/json");
// 假设你有三个变量分别为 fromValue、toValue、qValue
// 创建包含变量的 JSON 字符串
String jsonBody = String.format("{\"from\":\"%s\",\"to\":\"%s\",\"q\":\"%s\"}", fromLanguage, toLanguage, inputText);
// 创建 RequestBody 对象
RequestBody body = RequestBody.create(mediaType, jsonBody);
Request request = null;
try {
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();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
Response response = null;
try {
response = HTTP_CLIENT.newCall(request).execute();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
String json = null;
try {
json = response.body().string();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
Gson gson = new Gson();
// 将 JSON 数据解析为 JsonObject
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
// 获取 "result" 对象
JsonObject resultObject = jsonObject.getAsJsonObject("result");
// 获取 "trans_result" 数组
JsonArray transResultArray = resultObject.getAsJsonArray("trans_result");
// 获取第一个元素
JsonObject transResultObject = transResultArray.get(0).getAsJsonObject();
// 获取 "dst" 字段的值
String dstValue = transResultObject.get("dst").getAsString();
// 输出结果
outputLabel.setText(dstValue);
}
});
// 将组件添加到面板
panel.add(inputTextField, BorderLayout.NORTH);
panel.add(fromLanguageComboBox, BorderLayout.WEST);
panel.add(toLanguageComboBox, BorderLayout.EAST);
panel.add(translateButton, BorderLayout.CENTER);
panel.add(outputLabel, BorderLayout.SOUTH);
// 设置组件的外观
Font font = new Font("SimSun", Font.PLAIN, 14); // 设置字体为Verdana
inputTextField.setFont(font);
translateButton.setFont(font);
outputLabel.setFont(font);
fromLanguageComboBox.setFont(font);
toLanguageComboBox.setFont(font);
// 设置面板的背景色
panel.setBackground(new Color(240, 240, 240)); // 设置背景色为淡灰色
// 设置按钮和下拉框的边框
translateButton.setBorder(BorderFactory.createLineBorder(new Color(34, 139, 34), 2)); // 设置按钮边框为绿色
fromLanguageComboBox.setBorder(BorderFactory.createLineBorder(new Color(34, 139, 34), 1)); // 设置下拉框边框为绿色
toLanguageComboBox.setBorder(BorderFactory.createLineBorder(new Color(34, 139, 34), 1)); // 设置下拉框边框为绿色
// 将面板添加到主窗口
frame.getContentPane().add(panel);
// 设置窗口居中
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((screenSize.width - frame.getWidth()) / 2, (screenSize.height - frame.getHeight()) / 2);
// 设置窗口可见
frame.setVisible(true);
}
private String translateText(String inputText, String fromLanguage, String toLanguage) {
// 在这里可以添加实际的翻译逻辑
return inputText; // 这里先返回输入文本,表示没有进行实际翻译
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TranslationApp();
}
});
}
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();
try {
return new JSONObject(response.body().string()).getString("access_token");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}