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

时间:2012-12-12 14:30:37

标签: 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()返回正确写入的字符,但GUI中的实际TextArea显示没有文本。

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

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

}

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

1 个答案:

答案 0 :(得分:18)

您是否尝试在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));
        }
    }
}