0

I have a simple login window, and i want to show a JFXSpinner (like a loader) when i send the login request. For that, i have created a JFXSpinner object and initially i maked it invisible (setting the visibility value to false) and when the user click on the LOGIN button i want to show the spinner before sending the request and hide it again after finishing the request. The problem is : i can't show my JFXSpinner. can anyone help me please ?

This is my login methode

    //loader : is my JFXSpinner object
public void login(ActionEvent event)
{
    Task task = new javafx.concurrent.Task<Void>()
    {
            @Override
            protected Void call() throws Exception 
            {
                loader.setVisible(true);
                if(Compte.login(username.getText(), password.getText()))
                {
                    System.err.println("It's okey");
                }
                else
                {
                    //TODO
                }
                loader.setVisible(false);
                return null;
            }

            @Override
            protected void succeeded() 
            {
                loader.setVisible(false);
            }

            @Override
            protected void failed() 
            {
                loader.setVisible(false);
            }
    };
    Thread thread = new Thread(task, "My Task");
    thread.setDaemon(true);
    thread.start();
}
M.Lamine Lalmi
  • 78
  • 1
  • 2
  • 12

1 Answers1

1

You cannot modify the UI from a background thread, which is what happens when you try to call

loader.setVisible(true);

in the task's call() method.

Instead, you should make that call from the FX Application Thread, immediately before you start the task:

public void login(ActionEvent event) {
    Task task = new javafx.concurrent.Task<Void>() {

        @Override
        protected Void call() throws Exception  {
            if(Compte.login(username.getText(), password.getText())) {
                System.err.println("It's okey");
            } else {
                //TODO
            }
            return null;
        }

        @Override
        protected void succeeded() {
            loader.setVisible(false);
        }

        @Override
        protected void failed() {
            loader.setVisible(false);
        }

    };
    Thread thread = new Thread(task, "My Task");
    thread.setDaemon(true);
    loader.setVisible(true);
    thread.start();
}
James_D
  • 201,275
  • 16
  • 291
  • 322
  • 1
    Caveat: there may be other problems in your code: you only posted this method and not, for example, where `loader` is defined or added to the scene graph. – James_D May 10 '17 at 01:45