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

前端之家收集整理的这篇文章主要介绍了将System.out重定向到JavaFX中的TextArea前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
更新:

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

CoreTest中必须有一些阻止用户界面的东西,但是它可以做各种各样的东西(异步xmlrpc请求,异步http请求,文件io等),我试着把它全部放在runLater中,但是并没有帮助.

更新2:

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

更新3:

好的我修好了我不知道为什么,但是没有关于JavaFX的指南说这个,它的非常重要:

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

我有这个工作与Swing的JTextArea,但由于某些原因,它不适用于JavaFX.

我尝试调试,并在.getText()之后每次写入返回似乎是正确写入的字符,但在GUI中的实际TextArea显示没有文本.

我忘了刷新一下吗?

  1. TextArea ta = TextAreaBuilder.create()
  2. .prefWidth(800)
  3. .prefHeight(600)
  4. .wrapText(true)
  5. .build();
  6.  
  7. Console console = new Console(ta);
  8. PrintStream ps = new PrintStream(console,true);
  9. System.setOut(ps);
  10. System.setErr(ps);
  11.  
  12. Scene app = new Scene(ta);
  13. primaryStage.setScene(app);
  14. primaryStage.show();

和控制台类:

  1. import java.io.IOException;
  2. import java.io.OutputStream;
  3.  
  4. import javafx.scene.control.TextArea;
  5.  
  6. public class Console extends OutputStream
  7. {
  8. private TextArea output;
  9.  
  10. public Console(TextArea ta)
  11. {
  12. this.output = ta;
  13. }
  14.  
  15. @Override
  16. public void write(int i) throws IOException
  17. {
  18. output.appendText(String.valueOf((char) i));
  19. }
  20.  
  21. }

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

解决方法

你是否尝试在UI线程上运行它?
  1. public void write(final int i) throws IOException {
  2. Platform.runLater(new Runnable() {
  3. public void run() {
  4. output.appendText(String.valueOf((char) i));
  5. }
  6. });
  7. }

编辑

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

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

但是,如果需要几秒钟,您的GUI将不会在几秒钟内更新.您需要在单独的线程中运行这些任务.

为了记录,这工作正常(我删除文件和CoreTest位):

  1. public class Main extends Application {
  2.  
  3. @Override
  4. public void start(Stage primaryStage) throws IOException {
  5.  
  6. TextArea ta = TextAreaBuilder.create().prefWidth(800).prefHeight(600).wrapText(true).build();
  7. Console console = new Console(ta);
  8. PrintStream ps = new PrintStream(console,true);
  9. System.setOut(ps);
  10. System.setErr(ps);
  11. Scene app = new Scene(ta);
  12.  
  13. primaryStage.setScene(app);
  14. primaryStage.show();
  15.  
  16. for (char c : "some text".tocharArray()) {
  17. console.write(c);
  18. }
  19. ps.close();
  20. }
  21.  
  22. public static void main(String[] args) {
  23. launch(args);
  24. }
  25.  
  26. public static class Console extends OutputStream {
  27.  
  28. private TextArea output;
  29.  
  30. public Console(TextArea ta) {
  31. this.output = ta;
  32. }
  33.  
  34. @Override
  35. public void write(int i) throws IOException {
  36. output.appendText(String.valueOf((char) i));
  37. }
  38. }
  39. }

猜你在找的Java相关文章