0

I am on the main thread. When choosing an item from the menu a database has to be called before the gui can show the new panel. This takes some time. During this time I want to show the wait-cursor. I found a way but the code looks ugly. How could this be done more elegant? This question is different from others because the long running task is working on the gui.

menuitem.setOnAction(event -> {  szene.setCursor(Cursor.WAIT);
                               Task<Void> task = new Task<Void>()
                               {
                                  @Override 
                                  public Void call() throws Exception
                                  {
                                     Platform.runLater(new Runnable()
                                     {
                                        @Override
                                        public void run()
                                        {
                                            // do some stuff
                                            szene.setCursor(Cursor.DEFAULT);
                                        }
                                     });
                                     return null;
                                  };
                              }; 
                              new Thread(task).start();
                            });
  • 3
    Putting the entire `Task` logic inside `Platform.runLater` defeats the entire purpose of using a `Task`, as the logic would run on the UI thread, blocking updates (including cursor changes). – Itai Apr 19 '16 at 17:33
  • This way the cursor does change to wait status and back. The code works but it is ugly. –  Apr 21 '16 at 07:08
  • The long running task is updating the UI therefore it is correct to run it on the UI thread. I found a different question: http://stackoverflow.com/questions/27309642/javafx-updating-ui-from-a-thread-without-direct-calling-platform-runlater Maybe my solution is the correct one. –  Apr 21 '16 at 07:28

1 Answers1

1

You can use:

 Task<Void> task = new Task<Void>() {

            @Override
            protected Void call() throws Exception {
                //action
                return null;
            }
        };

 task.setOnSucceeded(e -> scene.setCursor(Cursor.DEFAULT));
 task.setOnFailed(e -> scene.setCursor(Cursor.DEFAULT));

 scene.setCursor(Cursor.WAIT);
 new Thread(task).start();
jns
  • 6,017
  • 2
  • 23
  • 28