1

What I'm trying to do is printing texts on textarea in real time even after the button is clicked.

When I click the button, the UI freezes until its job finishes, and after that, it prints all the texts together unlike System.out.println.

The code below is what I tried, and it doesn't work as I expected. UI just hangs and doesn't show me 'test' on textarea.

There's no need to use the listener, and it's okay to use appendText only, but I just can't find out how to let the ActionEvent for the button work without freezing the UI.

I will really appreciate your any help or much better code!!

final TextField announcement = new TextField();
    Platform.runLater(new Runnable() {
        @Override public void run() {
            announcement.textProperty().addListener(new javafx.beans.value.ChangeListener<String>() {
                        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                        textoutput.appendText(announcement.getText());
                        }
            });
        }
    });

btn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
        public void handle(ActionEvent event) { 
             announcement.setText("test");
             // bunch of codes below
        }
});
Keibee
  • 45
  • 1
  • 5

2 Answers2

1

Have you tried using Platform.runLater? I have code where I have long-running Tasks that periodically updates the UI using the Platform.runLater() calls. It does this by running the Runnable on the JavaFX application's main thread so it is executed separately from your long task.

E.g. (using Java8 lambdas - you could just pass in a new Runnable implementation instead; I prefer lambdas in this situation for clarity's sake):

btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
    public void handle(ActionEvent event) { 
         // Somewhere in your new Task()
         Platform.runLater(() -> {
             // Update UI
             announcement.setText("test");
         });
         // bunch of codes below
    }
});
matt1
  • 1,175
  • 7
  • 14
  • Even with platform.runlater, UI freezes as soon as I press the button, and shows all the text together, and "test" is on the last line.. – Keibee Sep 16 '14 at 15:51
0

The reason for this is that your event handler is executing on FX thread, so UI cannot be updated until it has finished. As already suggested by ItachiUchiha, you should put your code inside Task. When you need to update text in TextArea, use Tasks updateMessage() method. Put a ChangeListener on Tasks message property, and set text from within that listener.

Nikša Baldun
  • 1,854
  • 4
  • 28
  • 39