我想在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
}
}
答案 0 :(得分:6)
我刚刚做了这个并且有效。虽然大量的文字很慢。
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));
}