设法将我的控制台输出到JavaFX中的TextArea后,我试图实现下一步:使用一个不错的ListView。我已经把它钉了,它比简单的TextArea更好(消耗更少的资源),但我遇到了一个奇怪的问题。
首先,我以this question的答案为例 接受的答案中提出的代码工作得很好,但在我的情况下,它表现出一种奇怪的行为:我的输出在9个字符之后被拆分,有时候,一个字符缺失。
这是我用来设置我的控制台的方法:
private void setUpConsole() {
Console console = new Console(textAreaLog);
PrintStream ps = new PrintStream(console, true);
System.setOut(ps);
}
为了完整起见,这是我绑定到用于管理控制台重定向的线程的任务,从而使JavaFX GUI从繁重的负载中解脱出来:
private void consoleTask() {
Task<Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception {
setUpConsole();
return null;
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
}
这是我的控制台类,与上述链接中提出的类相同。
public class Console extends OutputStream {
private javafx.scene.control.ListView<String> output;
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
Console(javafx.scene.control.ListView<String> output) {
this.output = output;
}
private void addText() throws IOException {
String text = buffer.toString("UTF-8");
buffer.reset();
Platform.runLater(() -> output.getItems().add(text));
}
@Override
public void write(int b) throws IOException {
if (b == '\n') {
addText();
} else {
buffer.write(b);
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
int bound = off + len;
for (int i = off; i < bound; i++) {
if (i == '\n') {
buffer.write(b, off, i - off);
addText();
off = i + 1;
}
}
assert(off <= bound);
buffer.write(b, off, bound - off);
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void flush() throws IOException {
// outputs all currently buffered data as a new cell, without receiving
// a newline as otherwise is required for that
addText();
}
@Override
public void close() throws IOException {
flush();
buffer.close();
}
}
有关如何修复我的Console类以消除这种令人讨厌的行为的任何提示?