Show and wait for the response of the given JavaFX dialog . - Java JavaFX

Java examples for JavaFX:Dialog

Description

Show and wait for the response of the given JavaFX dialog .

Demo Code

/*//from   w ww. j  a  v  a 2 s .c om
     * Copyright 2015 Thierry Wasylczenko
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *   http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.stage.Stage;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main{
    /**
         * Show and wait for the response of the given {@code dialog}. This method ensures the dialog is displayed in the
         * JavaFX application thread.
         * @param dialog The dialog to show.
         * @return The answer of the user or {@code null} if no answer has been made.
         */
        private static ButtonType displayDialog(Dialog<ButtonType> dialog) {
    Optional<ButtonType> response = null;

    if(dialog != null) {
        final FutureTask<Optional<ButtonType>> future = new FutureTask<>(() -> dialog.showAndWait());
        PlatformHelper.run(future);
        try {
            response = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    return response != null && response.isPresent() ? response.get() : null;
}
}

Related Tutorials