11.20

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.IOException;

public class BaiduTranslateGUIExample extends Application {
    private static final String APP_ID = "api_key";
    private static final String SECRET_KEY = "secret_key";
    private static final String API_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("百度翻译GUI示例");

        // 输入文本区域
        TextArea inputTextArea = new TextArea();
        inputTextArea.setPromptText("请输入要翻译的文本");

        // 输出文本区域
        TextArea outputTextArea = new TextArea();
        outputTextArea.setEditable(false);

        // 翻译按钮
        Button translateButton = new Button("翻译");
        translateButton.setOnAction(event -> {
            String inputText = inputTextArea.getText().trim();
            String fromLang = "zh"; // 假设默认源语言为中文,可添加选择功能完善
            String toLang = "en"; // 假设默认目标语言为英文,可添加选择功能完善
            try {
                String translatedText = translate(inputText, fromLang, toLang);
                outputTextArea.setText(translatedText);
            } catch (IOException e) {
                outputTextArea.setText("翻译出错,请检查网络或配置");
                e.printStackTrace();
            }
        });

        VBox layout = new VBox(10);
        layout.setPadding(new Insets(10));
        layout.getChildren().addAll(new Label("输入文本:"), inputTextArea,
                new Label("翻译结果:"), outputTextArea, translateButton);

        Scene scene = new Scene(layout, 400, 300);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static String translate(String text, String from, String to) throws IOException {
        // 这里直接复用任务三的翻译函数,你可以根据实际情况调整或优化
        return BaiduTranslateExample.translate(text, from, to);
    }
}

 

posted @ 2024-12-31 15:15  酥饼馅红豆沙  阅读(8)  评论(0)    收藏  举报