My problem is that I have a JavaFX TextArea and want to update its contents in a separate thread to show new text instantly instead of a bunch after the method has finished. Say, for example, I wanted to build a timer. In the current case, the TextArea would show 10 at the beginning, then I would press the "Start" button, wait ten seconds and a zero shows up. If this works multithreaded, it would count down from ten to zero with all the numbers in between.
Here's a sample code:
TextArea textArea = new TextArea();
Button button = new Button("Start");
GridPane root = new GridPane();
root.add(textArea);
root.add(button);
button.setOnMouseClicked((event) -> {
new Thread(() -> {
for (int i = 10; i >= 0; i--) {
textArea.setText(Integer.parseInt(i));
try { Thread.sleep(1000); }
catch (InterruptedException ie) { ie.printStackTrace(); }
}
}).start();
});
This code ends in an IndexOutOfBoundsException
in the FX Application Thread
for me, which only shows up when the setOnMouseClicked
event is executed in another thread.
It works for both the "FX Application Thread" and the "Main" thread.