我正在努力一次打印一个“翻译文本 x / y”。目前,循环完成后会立即输出所有翻译进度。我正在使用的 JConsole 是一个基于 JFrame 的基本控制台,其中添加了一个 TextArea。
我的代码
System.out.println("Translating " + scrapedTextCollection.size() + " results...");
// Perform translation...
int count = 0;
for (Map<String, String> mappedText : scrapedTextCollection) {
count++;
MainClient.getClientExtension().getJConsole().writeInformation("Translating text" + count + " / " + scrapedTextCollection.size());
String translatedResult = Translator.translate(Language.valueOf("ENGLISH"), Language.valueOf("SPANISH"), mappedText.get("Title") + " - " + mappedText.get("Chunk Text"));
mappedText.put("Translated Text", translatedResult);
}
我尝试了各种方法,但都不起作用。任何帮助都会很棒。
import javax.swing.SwingWorker;
import java.util.List;
import java.util.Map;
public class TranslationTask extends SwingWorker<Void, String> {
private List<Map<String, String>> scrapedTextCollection;
private JConsole console;
public TranslationTask(List<Map<String, String>> scrapedTextCollection, JConsole console) {
this.scrapedTextCollection = scrapedTextCollection;
this.console = console;
}
@Override
protected Void doInBackground() {
int count = 0;
for (Map<String, String> mappedText : scrapedTextCollection) {
count++;
publish("Translating text " + count + " / " + scrapedTextCollection.size());
String translatedResult = Translator.translate(Language.valueOf("ENGLISH"), Language.valueOf("SPANISH"), mappedText.get("Title") + " - " + mappedText.get("Chunk Text"));
mappedText.put("Translated Text", translatedResult);
}
return null;
}
@Override
protected void process(List<String> chunks) {
for (String message : chunks) {
console.writeInformation(message);
}
}
@Override
protected void done() {
console.writeInformation("Translation complete.");
}
}
// Usage
TranslationTask task = new TranslationTask(scrapedTextCollection, MainClient.getClientExtension().getJConsole());
task.execute();
doInBackground()
:在单独的线程上运行。翻译过程发生在这里。
publish()
:将中间结果(进度消息)发送到
process()
方法。
process()
:在 EDT 上运行并使用消息更新 GUI。
done()
:在 EDT 之后运行
doInBackground()
完成。可以用来表示任务完成。
在
doInBackground()
中,每个文本都会被翻译,并发布进度消息。
process()
使用当前进度消息更新 GUI 中的 TextArea
。
此方法可确保您的 GUI 保持响应并实时更新进度。