我正在尝试创建一个将西班牙语翻译成英语的Java应用程序。我在将西班牙语翻译成英语时遇到问题。但是,当我将英语翻译成spansih时,它可以工作。这是我的代码。这是我的代码。你能告诉我我的错误吗?此代码现在可以正常工作,但是当我将fromLang的值从en更改为es时,它不起作用。
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
public class GuiApp1 {
private static final String CLIENT_ID = "FREE_TRIAL_ACCOUNT";
private static final String CLIENT_SECRET = "PUBLIC_SECRET";
private static final String ENDPOINT = "http://api.whatsmate.net/v1/translation/translate";
public static void main(String[] args) throws Exception {
GuiApp1 g = new GuiApp1();
JFrame f=new JFrame();//creating instance of JFrame
f.setAlwaysOnTop( true );
JButton b=new JButton("Translate");//creating instance of JButton
b.setBounds(90,150,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
JTextArea t1,t2;
t1=new JTextArea(2,2);
String spanish;
t1.setBounds(50,100, 200,30);
t2=new JTextArea(2,2);
t2.setBounds(50,200, 200,30);
f.add(t1); f.add(t2);
f.setPreferredSize(new Dimension(200, 900));
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String text = t1.getText();
text = text.trim();
text = text.toLowerCase();
System.out.println(text);
String fromLang = "en";
String toLang = "es";
//String text = "Cuál es su nombre";
try{
translate(fromLang, toLang, text);
}catch(Exception e){
System.out.println(e);
}
}
});
}
/**
* Sends out a WhatsApp message via WhatsMate WA Gateway.
*/
public static void translate(String fromLang, String toLang, String text) throws Exception {
// TODO: Should have used a 3rd party library to make a JSON string from an object
String jsonPayload = new StringBuilder()
.append("{")
.append("\"fromLang\":\"")
.append(fromLang)
.append("\",")
.append("\"toLang\":\"")
.append(toLang)
.append("\",")
.append("\"text\":\"")
.append(text)
.append("\"")
.append("}")
.toString();
URL url = new URL(ENDPOINT);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("X-WM-CLIENT-ID", CLIENT_ID);
conn.setRequestProperty("X-WM-CLIENT-SECRET", CLIENT_SECRET);
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(jsonPayload.getBytes());
os.flush();
os.close();
int statusCode = conn.getResponseCode();
System.out.println("Status Code: " + statusCode);
BufferedReader br = new BufferedReader(new InputStreamReader(
(statusCode == 200) ? conn.getInputStream() : conn.getErrorStream()
));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
}
也许您现在已经超出了10的免费试用使用限制。
在任何情况下,代码都有效。它将英语翻译成西班牙语,或者将西班牙语译成英语。您需要做的就是确保您可以选择要使用的翻译方向。当前,您还没有这个,并且正在通过默认的en转换为es。如果将fromLang变量内容更改为"es"
,并且将toLang变量内容更改为en
,并在JTextArea t1中输入西班牙语word,则按下翻译按钮,您将收到翻译到控制台窗口(而不是JTextArea,t2)的翻译。收到的字符串应放在JTextArea t2中。为了将返回的字符串放入JTextArea t2中,您将要使tranlate()方法返回String类型,然后在该方法底部的while循环中,将返回的数据发送到控制台的操作如下:
public static String translate(String fromLang, String toLang, String text) throws Exception {
// ... Most method code here ...
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output).append(System.lineSeparator());
System.out.println(output); // Optional - For testing
}
conn.disconnect();
return sb.toString();
}
现在,调用translate()方法的位置,请改为执行此操作:
try {
String translation = translate(fromLang, toLang, text);
t2.setText(translation);
}
catch (Exception e) {
System.out.println(e);
}
现在返回的翻译将放置在t2 JTextArea中。我已经进行了上述修改,并将其应用于下面提供的代码:
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.Border;
public class Translator {
private static final String CLIENT_ID = "FREE_TRIAL_ACCOUNT";
private static final String CLIENT_SECRET = "PUBLIC_SECRET";
private static final String ENDPOINT = "http://api.whatsmate.net/v1/translation/translate";
@SuppressWarnings("Convert2Lambda")
public static void main(String[] args) throws Exception {
Translator g = new Translator();
JFrame f = new JFrame();//creating instance of JFrame
f.setTitle("Translator");
f.setAlwaysOnTop(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(295, 300));
f.setLayout(null); //using no layout manager (*** BAD IDEA!! ***)
String[] transDirection = {"English To Spanish", "Spanish To English"};
JComboBox<String> jc = new JComboBox<>(transDirection);
jc.setSelectedIndex(0);
jc.setBounds(60, 30, 160, 25);
f.add(jc);
JButton b = new JButton("Translate");//creating instance of JButton
b.setBounds(90, 140, 100, 30);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
Border border = BorderFactory.createLineBorder(Color.decode("#33acff"));
JTextArea t1 = new JTextArea(2, 2);
t1.setBounds(40, 80, 200, 50);
t1.setBorder(border);
t1.setLineWrap(true);
t1.setWrapStyleWord(true);
JScrollPane sp1 = new JScrollPane(t1);
sp1.setBounds(40, 80, 200, 50);
// ---------------------
JTextArea t2 = new JTextArea(2, 2);
t2.setBounds(40, 180, 200, 50);
t2.setBorder(border);
t2.setLineWrap(true);
t2.setWrapStyleWord(true);
JScrollPane sp2 = new JScrollPane(t2);
sp2.setBounds(40, 180, 200, 50);
f.add(sp1, BorderLayout.CENTER);
f.add(sp2, BorderLayout.CENTER);
f.pack();
f.setVisible(true);//making the frame visible
f.setLocationRelativeTo(null); // Must be after setVisible().
t1.requestFocus(); // Set focus on t1 when started
// Button Action Listener...
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
String text = t1.getText().trim();
//Make sure there is text to translate...
if (text.equals("")) {
JOptionPane.showMessageDialog(f, "There is no text supplied to translate!",
"Translation Error!", JOptionPane.WARNING_MESSAGE);
return; // Get out of this event.
}
// Get selected language translation direction...
String fromLang = "";
String toLang = "";
switch (jc.getSelectedItem().toString().toLowerCase()) {
case "english to spanish":
fromLang = "en";
toLang = "es";
break;
case "spanish to english":
fromLang = "es";
toLang = "en";
break;
default:
fromLang = "en";
toLang = "es";
}
try {
String translation = translate(fromLang, toLang, text);
t2.setText(translation);
}
catch (Exception e) {
System.out.println(e);
}
}
});
}
/**
* Sends out a WhatsApp message via WhatsMate WA Gateway.<br><br>
* @param fromLang
* @param toLang
* @param text
* @return
* @throws java.lang.Exception
*/
public static String translate(String fromLang, String toLang, String text) throws Exception {
// TODO: Should have used a 3rd party library to make a JSON string from an object
String jsonPayload = new StringBuilder()
.append("{")
.append("\"fromLang\":\"")
.append(fromLang)
.append("\",")
.append("\"toLang\":\"")
.append(toLang)
.append("\",")
.append("\"text\":\"")
.append(text)
.append("\"")
.append("}")
.toString();
URL url = new URL(ENDPOINT);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("X-WM-CLIENT-ID", CLIENT_ID);
conn.setRequestProperty("X-WM-CLIENT-SECRET", CLIENT_SECRET);
conn.setRequestProperty("Content-Type", "application/json");
// 'Try With Resources' used here to auto-close stream.
try (OutputStream os = conn.getOutputStream()) {
os.write(jsonPayload.getBytes());
os.flush();
}
int statusCode = conn.getResponseCode();
System.out.println("Status Code: " + statusCode);
BufferedReader br = new BufferedReader(new InputStreamReader(
(statusCode == 200) ? conn.getInputStream() : conn.getErrorStream()
));
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output).append(System.lineSeparator());
System.out.println(output);
}
conn.disconnect();
return sb.toString();
}
}
附带说明:您可以选择在创建表单时不使用布局管理器(空)。 here's why这实际上是一个坏主意(请务必同时阅读注释)。