-->

重定向的System.out在JavaFX的一个TextArea(Redirecting Syste

2019-07-05 01:39发布

更新:

仍然有同样的问题,主要的应用程序代码修改的源程序: http://pastebin.com/fLCwuMVq

一定有什么东西在CoreTest阻止用户界面,但它做的东西各种各样的(异步XMLRPC请求,异步HTTP请求,文件IO等),我试图把一切都写进runLater但它不帮助。

更新2:

我验证代码运行并正确地产生输出,但UI组件不能管理,以显示它的年龄

更新3:

OK我固定它。 我不知道为什么,但没有关于JavaFX的导游说这个,它非常重要的:

始终把你的程序逻辑在一个单独的线程从Java FX线程


我有这个工作与Swing的JTextArea ,但由于某种原因,它不使用JavaFX工作。

我试着调试和并做.getText()每写返回什么似乎是正确写入字符后,但实际TextArea在GUI显示任何文本。

难道我忘了不知何故刷新它还是什么?

TextArea ta = TextAreaBuilder.create()
    .prefWidth(800)
    .prefHeight(600)
    .wrapText(true)
    .build();

Console console = new Console(ta);
PrintStream ps = new PrintStream(console, true);
System.setOut(ps);
System.setErr(ps);

Scene app = new Scene(ta);
primaryStage.setScene(app);
primaryStage.show();

Console类:

import java.io.IOException;
import java.io.OutputStream;

import javafx.scene.control.TextArea;

public class Console extends OutputStream
{
    private TextArea    output;

    public Console(TextArea ta)
    {
        this.output = ta;
    }

    @Override
    public void write(int i) throws IOException
    {
        output.appendText(String.valueOf((char) i));
    }

}

注:这是基于从溶液中这个答案 ,我删除了我也没在意,但未经修改的(除了从摆动变为JavaFX的),它有同样的结果位:写入UI元素的数据,没有数据展示屏幕。

Answer 1:

您是否尝试运行它的UI线程?

public void write(final int i) throws IOException {
    Platform.runLater(new Runnable() {
        public void run() {
            output.appendText(String.valueOf((char) i));
        }
    });
}

编辑

我觉得你的问题是,你运行的GUI线程,这是怎么回事,直到它完成冻结一切一些长期的任务。 我不知道是什么

CoreTest t = new CoreTest(installPath);
t.perform();

确实,但如果它需要几秒钟,你的GUI不会这几秒钟内更新。 你需要在一个单独的线程中运行这些任务。

根据记录,这工作正常(我已删除该文件,并CoreTest位):

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException {

        TextArea ta = TextAreaBuilder.create().prefWidth(800).prefHeight(600).wrapText(true).build();
        Console console = new Console(ta);
        PrintStream ps = new PrintStream(console, true);
        System.setOut(ps);
        System.setErr(ps);
        Scene app = new Scene(ta);

        primaryStage.setScene(app);
        primaryStage.show();

        for (char c : "some text".toCharArray()) {
            console.write(c);
        }
        ps.close();
    }

    public static void main(String[] args) {
        launch(args);
    }

    public static class Console extends OutputStream {

        private TextArea output;

        public Console(TextArea ta) {
            this.output = ta;
        }

        @Override
        public void write(int i) throws IOException {
            output.appendText(String.valueOf((char) i));
        }
    }
}


文章来源: Redirecting System.out to a TextArea in JavaFX