0

I have done the standard procedure of redirecting the console output to a textarea in JavaFX. Link of my implementation principle JavaFX: Redirect console output to TextArea that is created in SceneBuilder. However the problem is I am getting all the console output at once, i.e., the underlying program Action.run() does some work and produces console output intermediately. But in the GUI I'm getting all the output at once at the end of Action.run() execution. Is there any way to get the console output in real-time instead of the end?

@FXML
TextArea console;
private PrintStream ps;

public void initialize() {
    ps = new PrintStream(new Console(console),true);
}

public class Console extends OutputStream {
    private TextArea console;
 
    public Console(TextArea console) {
        this.console = console;
    }
 
    public void appendText(String valueOf) {
        Platform.runLater(() -> console.appendText(valueOf));
    }
 
    public void write(int b) throws IOException {
        appendText(String.valueOf((char)b));
    }
}

public void buttonAction(ActionEvent event) throws Exception {
    System.setOut(ps);
    System.setErr(ps);
    runButton.setDisable(true);
    Platform.runLater(new Runnable() {
        public void run() {
            try {
                Action action = new Action();
                action.run();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    });
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Arunavo
  • 34
  • 2
  • 8
  • 2
    Assuming `action.run()` is background work, don't execute it on the UI thread. That prevents the UI from redrawing (among other things). Also, you're assuming each individual byte maps to a character which, depending on the encoding, is not necessarily true; check out [this example](https://stackoverflow.com/questions/65405249/utf-8-encoding-for-output-from-console-to-javafx-textarea/65415420#65415420) of redirecting standard out to a text area. – Slaw Aug 05 '21 at 19:12
  • So, do I do this? ``` new Thread() { public void run() { Platform.runLater(new Runnable() { public void run() { try { runButton.setDisable(true); Analyzer analyzer = new Analyzer(ps); analyzer.runAnalysis(runType, analyzer_run_properties); } catch(Exception e) { e.printStackTrace(); } } }); } }.start();``` – Arunavo Aug 05 '21 at 19:16
  • What is `Action`? Could you provide a [mre]? – Slaw Aug 05 '21 at 19:18
  • It doesn't help even if I move it to a different thread. – Arunavo Aug 05 '21 at 19:28
  • 3
    From your comment you still are executing the work on the UI thread. Keep in mind what `Platform#runLater(Runnable)` does—it schedules the `Runnable` to execute on the UI thread at some point in the future. – Slaw Aug 05 '21 at 19:44
  • Thanks. It does work with the suggestions. – Arunavo Aug 05 '21 at 20:12

0 Answers0