package com.yangchong.fanyi;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.awt.event.ActionEvent;
public class Show extends JFrame {
private JPanel contentPane;
private JTextField input;
private JLabel label_1;
private JEditorPane rel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Show frame = new Show();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Show() {
setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Administrator\\Desktop\\logo.png"));
setResizable(false);
//设置窗体居中
// Toolkit kit = Toolkit.getDefaultToolkit();
// double w = kit.getScreenSize().getWidth();
// double h = kit.getScreenSize().getHeight();
// int width = 450;
// int height = 300;
// int x = (int) ((w-width)/2);
// int y = (int) ((h-height)/2);
setTitle("\u6709\u9053\u7FFB\u8BD1");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel("原文:");
label.setBounds(20, 25, 54, 15);
contentPane.add(label);
//原文输入框
input = new JTextField();
input.setBounds(73, 16, 255, 34);
//键盘事件
input.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int i = e.getKeyChar();
//监听回车按键事件
if(i == KeyEvent.VK_ENTER){
getRel();
}
}
});
contentPane.add(input);
input.setColumns(10);
//翻译按钮
JButton button = new JButton("翻译");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getRel();
}
});
button.setBounds(338, 21, 93, 23);
contentPane.add(button);
label_1 = new JLabel("\u8BD1\u6587\uFF1A");
label_1.setBounds(20, 76, 54, 15);
contentPane.add(label_1);
rel = new JEditorPane();
rel.setBounds(73, 76, 351, 176);
contentPane.add(rel);
}
public void getRel() {
String nr = input.getText();//获得用户输入的原文
try {
Fanyi.fanyi(nr);
String jg = null;
if(nr.matches("^[\u4e00-\u9fa5]{0,}$")){
jg = Fanyi.parserChinese(nr);
}else if(nr.matches("^[a-zA-Z]+$")){
jg = Fanyi.parserEnglish(nr);
}
rel.setText(jg);//输出翻译结果
} catch (IOException e1) {
JOptionPane.showMessageDialog(contentPane, "网络异常");
} catch (NullPointerException e2){
JOptionPane.showMessageDialog(contentPane, "未找到结果");
}
}
}