Java程序设计:选实验5 GUI初级应用

使用JLabel、JTextArea、JButton等控件实现句子的中译英demo,该demo包含四个文本框,在第一个文本框输入一句英文,在第二个和第三个文本框显示该句的英文翻译(要求使用百度翻译API、有道翻译API或其他API中的两种;自行上网查找如何调用这些API),在第四个文本框显示两个翻译的相同之处。

package 选实验5;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class TransApi {
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private String appid;
    private String securityKey;

    public TransApi(String appid, String securityKey) {
        this.appid = appid;
        this.securityKey = securityKey;
    }

    public String getTransResult(String query, String from, String to) throws UnsupportedEncodingException {
        Map params = buildParams(query, from, to);
        return HttpGet.get(TRANS_API_HOST, params);
    }

    private Map buildParams(String query, String from, String to) throws UnsupportedEncodingException {
        Map params = new HashMap();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

}
package 选实验5;

import com.youdao.aicloud.translate.utils.AuthV3Util;
import com.youdao.aicloud.translate.utils.HttpUtil;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 网易有道智云翻译服务api调用demo
 * api接口: https://openapi.youdao.com/api
 */
public class YoudaoTransApi {

	private static final String APP_ID = "XXXXXXXXXX"; 
    private static final String APP_KEY = "XXXXXXXXXX";     // 您的应用ID
    private static final String APP_SECRET = "XXXXXXXXXX";  // 您的应用密钥

    public static String getTransResult(String query, String from, String to)  throws NoSuchAlgorithmException {
        // 添加请求参数
        Map params = createRequestParams(query, from, to);
        // 添加鉴权相关参数
        AuthV3Util.addAuthParams(APP_KEY, APP_SECRET, params);
        // 请求api服务
        byte[] result = HttpUtil.doPost("https://openapi.youdao.com/api", null, params, "application/json");
        // 打印返回结果
        String str = String.valueOf(result);
        return str;
    }

    private static Map createRequestParams(String query, String from, String to) {
        /*
         * note: 将下列变量替换为需要请求的参数
         * 取值参考文档: https://ai.youdao.com/DOCSIRMA/html/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E7%BF%BB%E8%AF%91/API%E6%96%87%E6%A1%A3/%E6%96%87%E6%9C%AC%E7%BF%BB%E8%AF%91%E6%9C%8D%E5%8A%A1/%E6%96%87%E6%9C%AC%E7%BF%BB%E8%AF%91%E6%9C%8D%E5%8A%A1-API%E6%96%87%E6%A1%A3.html
         */

        return new HashMap() {{
            put("q", new String[]{q});
            put("from", new String[]{from});
            put("to", new String[]{to});
            put("vocabId", new String[]{APP_ID});
        }};
    }
}
package 选实验5;

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

public class Translation {
    private TransApi transApi;
    private JTextArea inputTextArea;
    private JTextArea baiduOutputTextArea;
    private JTextArea youdaoOutputTextArea;
    private JTextArea commonOutputTextArea;

    public Translation(String baiduAppId, String baiduSecurityKey) {
        transApi = new TransApi(baiduAppId, baiduSecurityKey);

        JFrame frame = new JFrame("中英文翻译演示");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 400);
        frame.setLocationRelativeTo(null);
        frame.setLayout(new BorderLayout());

        // 创建输入区域
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new FlowLayout());
        JLabel inputLabel = new JLabel("请输入中文:");
        inputTextArea = new JTextArea(3, 20);
        inputPanel.add(inputLabel);
        inputPanel.add(new JScrollPane(inputTextArea));

        // 创建翻译结果区域
        JPanel outputPanel = new JPanel();
        outputPanel.setLayout(new GridLayout(3, 2));

        JLabel baiduLabel = new JLabel("百度翻译结果:");
        baiduOutputTextArea = new JTextArea(3, 20);
        baiduOutputTextArea.setEditable(false);
        JScrollPane baiduScrollPane = new JScrollPane(baiduOutputTextArea);

        JLabel youdaoLabel = new JLabel("有道翻译结果:");
        youdaoOutputTextArea = new JTextArea(3, 20);
        youdaoOutputTextArea.setEditable(false);
        JScrollPane youdaoScrollPane = new JScrollPane(youdaoOutputTextArea);

        JLabel commonLabel = new JLabel("相同之处:");
        commonOutputTextArea = new JTextArea(3, 20);
        commonOutputTextArea.setEditable(false);
        JScrollPane commonScrollPane = new JScrollPane(commonOutputTextArea);

        outputPanel.add(baiduLabel);
        outputPanel.add(baiduScrollPane);
        outputPanel.add(youdaoLabel);
        outputPanel.add(youdaoScrollPane);
        outputPanel.add(commonLabel);
        outputPanel.add(commonScrollPane);

        // 创建翻译按钮
        JButton translateButton = new JButton("翻译");
        translateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
					translateButtonClicked();
				} catch (NoSuchAlgorithmException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
            }
        });

        // 将输入区域、翻译结果区域和翻译按钮添加到 JFrame
        frame.add(inputPanel, BorderLayout.NORTH);
        frame.add(translateButton, BorderLayout.CENTER);
        frame.add(outputPanel, BorderLayout.SOUTH);

        frame.setVisible(true);
    }

    private void translateButtonClicked() throws NoSuchAlgorithmException {
        String inputText = inputTextArea.getText();
        if (!inputText.isEmpty()) {
            try {
                // 使用 Baidu 翻译
                String baiduTranslation = transApi.getTransResult(inputText, "zh", "en");
                // 截取 "dst" 部分
                int startIndex = baiduTranslation.indexOf("\"dst\":\"") + 7;
                int endIndex = baiduTranslation.indexOf("\"", startIndex);
                String dst1 = baiduTranslation.substring(startIndex, endIndex);
                // 移除前导空格
                dst1 = dst1.trim();
                baiduOutputTextArea.setText(dst1);

                // 使用 Youdao 翻译
                String youdaoTranslation = YoudaoTransApi.getTransResult(inputText, "zh", "en");; // 请调用有道翻译 API 获取翻译结果
                // 截取 "dst" 部分
                startIndex = youdaoTranslation.indexOf("\"dst\":\"") + 7;
                endIndex = youdaoTranslation.indexOf("\"", startIndex);
                String dst2 = youdaoTranslation.substring(startIndex, endIndex);
                // 移除前导空格
                dst2 = dst2.trim();
                youdaoOutputTextArea.setText(dst2);

                // 查找相同之处
                String commonText = findCommon(dst1,dst2);
                commonOutputTextArea.setText(commonText);

            } catch (IOException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, "翻译错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "请输入要翻译的中文句子。", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private String findCommon(String text1, String text2) {
    	    String[] words1 = text1.split("\\s+");
    	    StringBuilder reStringBuilder = new StringBuilder();

    	    for (String word1 : words1) {
    	        if (text2.contains(word1)) {
    	            reStringBuilder.append(word1).append(" ");
    	        }
    	    }
    	    String commonWords = reStringBuilder.toString().trim();	    
    	    return commonWords;
    }


    public static void main(String[] args) {
        String baiduAppId = "XXXXXXXXXX";
        String baiduSecurityKey = "XXXXXXXXXX";

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Translation(baiduAppId, baiduSecurityKey);
            }
        });
    }
}

运行效果:

Java程序设计:选实验5 GUI初级应用_第1张图片Java程序设计:选实验5 GUI初级应用_第2张图片

Java程序设计:选实验5 GUI初级应用_第3张图片Java程序设计:选实验5 GUI初级应用_第4张图片

你可能感兴趣的:(Java,java,开发语言)