java - 将控制台输出重定向到 JavaFX TextArea?

标签 java javafx console fxml

我想在 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/

相关文章:

java - Jenkins 中的堆空间问题

JavaFX ImageView (FXML) 不显示/更改图片

linux - 如何在 Linux 上的命令行(控制台模式)中列出 upnp 服务器/渲染器?

java - Webflux Reactive 对象在渲染 Thymeleaf View 之前未解析

java - 未检测到 MouseListener

user-interface - 如何在JavaFX的ListView中获取项目的位置?

scripting - 在 TF2 脚本中转义双引号

delphi - 重复循环内的 Pascal for 循环

java - JPA- hibernate : UniqueConstraint on OneToOne & ManyToOne JoinColumns

javafx-2 - Javafx 组合框样式