Alex Jone Alex Jone - 1 month ago 13
Java Question

How to make sure UI updates before continuing

I'm new to JavaFX, and I have a button which initiates and object and does some methods with it. The problem is that the UI doesn't update until after the object performs the methods. When I click the button, the GUI doesn't respond (it says "(Not responding)" in the title bar. After the methods are finished, the UI updates. The only way I could see fixing this is waiting for the UI to update and then perform the methods. Is there any other way? How do I fix this?

Object myObj;
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
/* some ui updates */
myLabel.setText("something");
try {
/* try initiating object and doing some methods with them */
myObj = new Object();
myObj.doMethod();

Answer Source

You have to create a new thread for the time consuming method: (I'm also rewriting your code with lambda expressions... Java8 style ;))

Object myObj;
btn.setOnAction((ActionEvent event)->{
    /* some ui updates */
    myLabel.setText("something");
    try {
        /* try initiating object and doing some methods with them */
        Runnable timeConsumingTask = ()-> {
            myObj = new Object();
            myObj.doMethod();
        }
        Thread thread = new Thread(timeConsumingTask);
        thread.start();