Java電子英漢詞典是一款基于Java語言開發的小型應用軟件,用于英漢互譯。
一、設計思路
1. 界面設計
采用Swing GUI界面,包括一個文本框和一個翻譯按鈕。
JLabel label = new JLabel("請輸入要翻譯的單詞:"); JTextField textField = new JTextField(20); JButton button = new JButton("翻譯");
2. 功能設計
利用有道翻譯API實現英漢互譯功能。
//連接有道翻譯API String urlStr = "http://fanyi.youdao.com/openapi.do"; urlStr += "?keyfrom=youdaotest&key=1718914161&type=data&doctype=json&version=1.1&q="; urlStr += text; URL url = new URL(urlStr); URLConnection connection = url.openConnection(); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { //解析有道翻譯API返回的JSON數據 JSONObject json = JSONObject.parseObject(line); JSONArray array = json.getJSONArray("translation"); result = array.getString(0); } reader.close();
二、代碼實現
完整代碼如下:
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class MyDictionary extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private JLabel label; private JTextField textField; private JButton button; private String result; public MyDictionary() { super("電子英漢詞典"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setSize(400, 200); setResizable(false); setLayout(null); label = new JLabel("請輸入要翻譯的單詞:"); label.setBounds(30, 30, 150, 30); add(label); textField = new JTextField(20); textField.setBounds(170, 30, 150, 30); add(textField); button = new JButton("翻譯"); button.setBounds(150, 90, 100, 30); button.addActionListener(this); add(button); setAlwaysOnTop(true); setVisible(true); } public void actionPerformed(ActionEvent e) { String text = textField.getText().trim(); if (text.length() == 0) { result = "請輸入要翻譯的單詞!"; } else { result = translate(text); } JOptionPane.showMessageDialog(null, result); } private String translate(String text) { String result = ""; try { //連接有道翻譯API String urlStr = "http://fanyi.youdao.com/openapi.do"; urlStr += "?keyfrom=youdaotest&key=1718914161&type=data&doctype=json&version=1.1&q="; urlStr += text; URL url = new URL(urlStr); URLConnection connection = url.openConnection(); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { //解析有道翻譯API返回的JSON數據 JSONObject json = JSONObject.parseObject(line); JSONArray array = json.getJSONArray("translation"); result = array.getString(0); } reader.close(); } catch (Exception e) { e.printStackTrace(); } return result; } public static void main(String[] args) { new MyDictionary(); } }
上一篇css中name是什么
下一篇css中這么用模板