将控制台输出重定向到 JavaFX TextArea? [英] Redirect Console Output to JavaFX TextArea?

查看:56
本文介绍了将控制台输出重定向到 JavaFX TextArea?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 JavaFX TextArea 中显示控制台输出......不幸的是,我找不到任何适用于 JavaFX 的工作示例,但仅适用于 Java Swing,这在我的情况下似乎不起作用.

I want to show the console output in a JavaFX TextArea... unfortunately I cannot find any working example for JavaFX but only for Java Swing, which not seems to work in my case.

我试着按照这个例子:http://unserializableone.blogspot.ch/2009/01/redirecting-systemout-and-systemerr-to.html

并扩展我的代码,如下所示.但是,Eclipse IDE 中不再有控制台输出,TextArea 中也没有输出.知道我哪里做错了吗?

and extended my code as shown below. However, there is no console output anymore in my Eclipse IDE but also no output in my TextArea. Any idea where I am doing wrong?

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

}
}

推荐答案

我刚刚做了这个并且它奏效了.虽然文本量很大,但速度很慢.

I just did this and it worked. Though it was very slow with large amounts of text.

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));
}

这篇关于将控制台输出重定向到 JavaFX TextArea?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆