我想在 JavaFX TextArea 中显示控制台输出...不幸的是,我找不到任何适用于 JavaFX 的示例,只能找到适用于 Java Swing 的示例,这在我的情况下似乎不起作用。
编辑:
我试着按照这个例子:http://unserializableone.blogspot.ch/2009/01/redirecting-systemout-and-systemerr-to.html
并扩展了我的代码,如下所示。但是,在我的 Eclipse IDE 中不再有控制台输出,在我的 TextArea 中也没有输出。知道我哪里做错了吗?
public class Activity extends OutputStream implements Initializable {
@FXML
public static TextArea taRecentActivity;
public Activity() {
// TODO Auto-generated constructor stub
}
@Override
public void initialize(URL location, ResourceBundle resources) {
OutputStream out = new OutputStream() {
@Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
private void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
taRecentActivity.appendText(text);
}
});
}
@Override
public void write(int arg0) throws IOException {
// TODO Auto-generated method stub
}
}
最佳答案
我刚刚做了这个并且成功了。虽然它在处理大量文本时速度很慢。
public void appendText(String str) {
Platform.runLater(() -> textField.appendText(str));
}
和
@Override
public void initialize(URL location, ResourceBundle resources) {
OutputStream out = new OutputStream() {
@Override
public void write(int b) throws IOException {
appendText(String.valueOf((char) b));
}
};
System.setOut(new PrintStream(out, true));
}
关于java - 将控制台输出重定向到 JavaFX TextArea?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26874701/