Search code examples
javamultithreadingjavafxmessagebox

Wait in other thread for answer from Messagebox


I have a working class (Synchronization.java in my case) with static methods that uploads/downloads some data from and to the server. In some cases, I want to open a (JavaFX) MessageDialog (MessageBox) and ask the user if he wants to do a certain activity or not (answers: yes/no). To open this MessageDialog I need the controller from the main window and the stage. Moreover, as I am on another thread I can open the MessageBox in the UI-thread with Platform#runlater. The Synchronization.java should wait until I get the user's response from the MessageDialog (which is in the other thread) - i.e. after I get the response from the user, the corresponding method should be called.

Edit: I found a solution which I added as an answer. However, I am not fully convinced that this is the best solution for my problem. If anyone has a suggestion, thanks for sharing!


Solution

  • I solved it with the code below. This works, but I have the feeling, that there are better ways...

    public static boolean showMessageCheckToUpload() {
       @SuppressWarnings({ "unchecked", "rawtypes" })
       final FutureTask query = new FutureTask(new Callable() {
          @Override
          public Object call() throws Exception {
             boolean uploadDisk = MessageBoxTwoChoicesController.showDialogBox(
                        stage, "Upload disk",
                        "Do you want to upload the current Disk to the server?", "Yes", "No");
             return uploadDisk;
          }
        });
        Platform.runLater(query);
        try {
           return (boolean) query.get();
        } catch (InterruptedException | ExecutionException e) {
           return false;
        }
    }