如果可能,将信息从Java打印流发送到JTextPane的最佳方式是什么?
在Java中,我有一个将XML元数据从一个标准转换为另一个标准的包。该包最终通过单个函数访问,并通过PrintStream对象发送其所有输出。发送的输出只是每个文件的状态以及是否已翻译 如果我只是打印到System.out,这是非常好和漂亮的,但实际上我想在它转换时将其打印到JTextPane(有点像进度文本框)。翻译完XML后只打印状态并没有什么大不了的,但是由于可能有数千个XML文件,这是不可行的 我尝试过的一件事是使用一个线程,它从PrintStream(附加到ByteArrayOutputStream)获取所有信息,并让它将任何新信息发送到文本窗格。不幸的是,这仍然会在翻译结束时一次发送所有信息。对于System.out,这确实正常工作 下面是执行翻译并尝试显示输出的代码:如果可能,将信息从Java打印流发送到JTextPane的最佳方式是什么?,java,swing,multithreading,printstream,Java,Swing,Multithreading,Printstream,在Java中,我有一个将XML元数据从一个标准转换为另一个标准的包。该包最终通过单个函数访问,并通过PrintStream对象发送其所有输出。发送的输出只是每个文件的状态以及是否已翻译 如果我只是打印到System.out,这是非常好和漂亮的,但实际上我想在它转换时将其打印到JTextPane(有点像进度文本框)。翻译完XML后只打印状态并没有什么大不了的,但是由于可能有数千个XML文件,这是不可行的 我尝试过的一件事是使用一个线程,它从PrintStream(附加到ByteArrayOutpu
public class ConverterGUI extends javax.swing.JFrame {
boolean printToResultsBox = false;
PrintStream printStream = null;
ByteArrayOutputStream baos = null;
private class ResultsPrinter implements Runnable {
public ResultsPrinter() {
baos = new ByteArrayOutputStream();
printStream = new PrintStream(baos);
}
public void run() {
String tempString = "";
while (printToResultsBox) {
try {
if (!baos.toString().equals(tempString)) {
tempString = baos.toString();
resultsBox.setText(tempString);
}
} catch (Exception ex) {
}
}
}
}
...
ResultsPrinter rp = new ResultsPrinter();
Thread thread = new Thread(rp);
thread.start();
// Do the translation.
try {
printToResultsBox = true;
boolean success = false;
TranslationEngine te = new TranslationEngine();
// fileOrFolderToConvert is a text box in the GUI.
// linkNeeded and destinationFile are just parameters for the translation process.
success = te.translate(fileOrFolderToConvert.getText(), linkNeeded, destinationFile, printStream);
if (success) {
printStream.println("File/folder translation was a success.");
}
resultsBox.setText(baos.toString());
} catch (Exception ex) {
printStream.println("File translation failed.");
} finally {
printToResultsBox = false;
}
...
}
最终,在所有翻译完成后,这段代码会很好地打印到JTextPane,但不会打印到JTextPane。有什么建议吗?是否需要将PrintStream更改为其他内容?线程工作方式的问题在于更新结果框时您不在UI事件线程上。看看这门课。或者你甚至可以使用