package fanyi;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI extends JFrame implements ActionListener {
private JTextField originalText;
private JTextField translatedText;
private JComboBox<String> originalLanguage;
private JComboBox<String> translatedLanguage;
private JButton translateButton;
public GUI() {
setTitle("翻译");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
setResizable(false);
// 创建GUI组件
JLabel originalLabel = new JLabel("原文:");
JLabel translatedLabel = new JLabel("译文:");
originalText = new JTextField(20);
translatedText = new JTextField(20);
String[] languages = {"中文", "英文", "法文", "德文", "日文", "韩文"};
originalLanguage = new JComboBox<>(languages);
translatedLanguage = new JComboBox<>(languages);
translateButton = new JButton("翻译");
translateButton.addActionListener(this);
// 设置组件位置和样式
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(10, 10, 10, 10);
gbc.anchor = GridBagConstraints.CENTER;
add(originalLabel, gbc);
gbc.gridy = 1;
add(originalText, gbc);
gbc.gridy = 2;
add(originalLanguage, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
add(translatedLabel, gbc);
gbc.gridy = 1;
add(translatedText, gbc);
gbc.gridy = 2;
add(translatedLanguage, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
add(translateButton, gbc);
pack();
setLocationRelativeTo(null); // 居中显示窗口
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == translateButton) {
String YuanWen = originalText.getText();
String YuanWenYuYan = (String) originalLanguage.getSelectedItem();
String YiWenYuYan = (String) translatedLanguage.getSelectedItem();
// 调用翻译方法
Baidu baidu = new Baidu();
String translated = baidu.FanYi(YuanWen, YuanWenYuYan,YiWenYuYan);
// 将翻译结果显示在译文框中
translatedText.setText(translated);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
}
}