一个关于swing实时翻译的java文件
首先是我的架构,分别是启动,百度api接口的调用文件,swing的界面设计文件
其中的依赖是酱紫的(自己敲)
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency>
以下是代码,拿来能直接交
API.java
package translation; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Api { String baseUrl = "https://fanyi-api.baidu.com/api/trans/vip/translate"; String from = "auto"; String to = "zh"; String appid = "填你自己申请的"; String salt = "填你自己申请的"; String sign ; String answer=""; public boolean choose_language(String to){ if(to == null){ return true; } else if(to.equals("中文")){ this.to = "zh"; return true; } else if(to.equals("英文")){ this.to = "en"; return true; } else if(to.equals("日文")){ this.to = "jp"; return true; } else if(to.equals("泰文")){ this.to = "th"; return true; } else if(to.equals("粤语")){ this.to = "yue"; return true; } else { return false; } } public boolean get(String q) { try { // 创建 URL 对象 System.out.println(q); if(q == null){ q = ""; } this.sign = MD5(appid+q+salt+"FA0i9T87VzmfD_p7QmTW"); String urlWithParams = this.baseUrl + "?q=" + URLEncoder.encode(q, "UTF-8") + "&from=" + URLEncoder.encode(this.from, "UTF-8") + "&to=" + URLEncoder.encode(this.to, "UTF-8") + "&appid=" + URLEncoder.encode(this.appid, "UTF-8") + "&salt=" + URLEncoder.encode(this.salt, "UTF-8") + "&sign=" + URLEncoder.encode(this.sign, "UTF-8"); System.out.println(urlWithParams); URL url = new URL(urlWithParams); // 创建 HttpURLConnection 对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法(GET、POST 等) connection.setRequestMethod("GET"); // // 可选:设置请求头部信息 // connection.setRequestProperty("Content-Type", "application/json"); // connection.setRequestProperty("Authorization", "Bearer YourAccessToken"); // 发送请求 int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); // 获取输入流,用于读取返回的数据 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; // 读取数据 while ((line = reader.readLine()) != null) { response.append(line); } JsonObject jsonObject = JsonParser.parseString(response.toString()).getAsJsonObject(); // 在这里处理解析后的 JSON 数据 System.out.println("Parsed JSON: " + jsonObject.toString()); System.out.println(jsonObject.get("trans_result").getAsJsonArray().get(0).getAsJsonObject().get("dst")); answer = String.valueOf(jsonObject.get("trans_result").getAsJsonArray().get(0).getAsJsonObject().get("dst")); // 关闭连接 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return true; } private static String MD5(String s) { try { // 获取 MD5 摘要算法实例 MessageDigest md = MessageDigest.getInstance("MD5"); // 将输入字符串转换为字节数组 byte[] byteData = s.getBytes(); // 计算摘要 byte[] mdBytes = md.digest(byteData); // 将字节数组转换为十六进制字符串 StringBuilder result = new StringBuilder(); for (byte mdByte : mdBytes) { result.append(Integer.toString((mdByte & 0xff) + 0x100, 16).substring(1)); } return result.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } public String get_answer(){ String temp = this.answer; this.answer=""; return temp; } }
Main.java
package ui; import translation.Api; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; public class Main { public void display(String result, ArrayList<String> strArray){ Font font = new Font("仿宋", Font.PLAIN, 25); JFrame jf =new JFrame(); JPanel Jp = new JPanel();//申请容器 jf.setLayout(null); jf.setSize(560, 400);//设置窗体大小 jf.setLocationRelativeTo(null);//设置窗体于屏幕中央位置 jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//点击叉叉可以关闭窗体 jf.setVisible(true);//组件可见 Jp.setLayout(null); jf.setResizable(false);//窗体不可变大或者变小 jf.setContentPane(Jp);//不知道 JLabel jLabel=new JLabel("翻译结果为:"); jLabel.setVisible(true); jLabel.setFont(font); jLabel.setBounds(20,20,240,30); Jp.add(jLabel); final JLabel res=new JLabel(result); res.setVisible(true); res.setFont(font); res.setBounds(60,60,420,180); Jp.add(res); JLabel jLabel2=new JLabel("请输入:"); jLabel2.setVisible(true); jLabel2.setFont(font); jLabel2.setBounds(20,250,100,30); Jp.add(jLabel2); final JTextField input=new JTextField(10); input.setVisible(true); input.setFont(font); input.setBounds(120,250,220,30); Jp.add(input); final JComboBox comboBox = new JComboBox(); for (String item : strArray) { comboBox.addItem(item); } comboBox.setVisible(true); comboBox.setFont(font); comboBox.setBounds(340,250,80,30); Jp.add(comboBox); JButton jButton = new JButton("提交"); jButton.setVisible(true); jButton.setFont(font); jButton.setBounds(430,250,85,30); Jp.add(jButton); jButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Api api=new Api(); api.choose_language((String) comboBox.getSelectedItem()); if(api.get(input.getText())){ try { JlabelSetText(res,api.get_answer()); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); } } } }); } void JlabelSetText(JLabel jLabel, String longString) throws InterruptedException { StringBuilder builder = new StringBuilder("<html>"); char[] chars = longString.toCharArray(); FontMetrics fontMetrics = jLabel.getFontMetrics(jLabel.getFont()); int start = 0; int len = 0; while (start + len < longString.length()) { while (true) { len++; if (start + len > longString.length())break; if (fontMetrics.charsWidth(chars, start, len) > jLabel.getWidth()) { break; } } builder.append(chars, start, len-1).append("<br/>"); start = start + len - 1; len = 0; } builder.append(chars, start, longString.length()-start); builder.append("</html>"); jLabel.setText(builder.toString()); } }
mian.java(启动!)
import translation.Api; import ui.Main; import java.util.ArrayList; public class mian { public static void main(String[] args) { Main main=new Main(); ArrayList<String> arrayList=new ArrayList<String>(); arrayList.add("中文"); arrayList.add("英文"); arrayList.add("日文"); arrayList.add("泰文"); arrayList.add("粤语"); main.display("",arrayList); } }
百度翻译的接口,具体名称好像叫通用文本翻译,对了泰语好像不行,然后。。。无