将System.out重定向到JavaFX中的TextArea

Dre*_*een 16 java textarea javafx io-redirection printstream

更新:

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

必须有一些东西CoreTest阻止UI,但它做各种各样的东西(异步xmlrpc请求,异步http请求,文件io等),我尝试把它全部插入,runLater但它没有帮助.

更新2:

我验证了代码运行并正确生成输出,但UI组件无法管理显示它多年

更新3:

好的我修好了.我不知道为什么,但没有关于JavaFX的指导说明这一点,而且非常重要:

始终将程序逻辑放在与Java FX线程不同的线程中


我有这个使用Swing的,JTextArea但由于某种原因它不适用于JavaFX.

我尝试调试它并.getText()在每次写入后执行返回正确写入的字符,但TextAreaGUI中的实际显示没有文本.

我忘了以某种方式刷新它或什么?

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();
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

注意:这是基于这个答案的解决方案,我删除了我不关心但未修改的位(除了从Swing更改为JavaFX),它有相同的结果:写入UI元素的数据,没有数据显示在屏幕.

ass*_*ias 18

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

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

编辑

我认为你的问题是你在GUI线程中运行一些长任务,这将冻结所有内容直到它完成.我不知道是什么

CoreTest t = new CoreTest(installPath);
t.perform();
Run Code Online (Sandbox Code Playgroud)

但是,如果需要几秒钟,那么您的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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)