Java FX новое модальное окно в задаче - PullRequest
0 голосов
/ 07 мая 2018

Моя проблема в том, что я не могу запустить новое модальное окно в Task, оно просто не выходит. Я не понимаю, как из Task можно извлечь не просто аллерт, а любое модальное окно. Перевод от Google =)

Task<Void> task = new Task<Void>() {
            @Override 
            public Void call() throws ApiException,ClientException,InterruptedException {
                 int i = 0;
                 for ( i = 0; i < bufferLenght; i++){
                    try {
                    ...some code
                    }catch(ApiCaptchaException e) {
                       ...get capcha
                       captchaSid = e.getSid();
                       captchaImg = e.getImage();
                       System.out.println( captchaSid);
}

                    System.out.println(captchaSid);
                    if (captchaSid != null) {
                        System.out.println("gg");
                        Alert alert = new Alert(AlertType.INFORMATION);
                        alert.setTitle("Test Connection");
                        //here he is stuck
                        alert.setHeaderText("Results:");
                        alert.setContentText("Connect to the database successfully!");
                        alert.showAndWait();

                        System.out.println("gg3");  
                    if(i<bufferLenght-1) {
                    Thread.sleep(2000);
                    }
                }
                return null;
            }
        };

        new Thread(task).start();

1 Ответ

0 голосов
/ 07 мая 2018

Вы должны создать и показать новые окна в ветке приложения FX. Вы можете запланировать выполнение кода в потоке приложений FX, отправив его на Platform.runLater(...). Если вам нужен фоновый поток, чтобы дождаться, пока пользователь отклонит Alert, вы можете использовать CompletableFuture, как в этот вопрос :

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

    @Override
    protected Void call() throws Exception {

        // ...

        CompletableFuture.runAsync(() -> {
            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("Test Connection");
            alert.setHeaderText("Results:");
            alert.setContentText("Connect to the database successfully!");
            alert.showAndWait();
        }, Platform::runLater).join();

        // ...
    }
};

Если ваше оповещение возвращает нужное вам значение, используйте supplyAsync(...) и возвращайте значение из лямбда-выражения. Затем вы можете присвоить это значение результату join():

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

    @Override
    protected Void call() throws Exception {

        // ...

        String result = CompletableFuture.supplyAsync(() -> {
            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("Test Connection");
            alert.setHeaderText("Results:");
            alert.setContentText("Connect to the database successfully!");
            alert.showAndWait();
            // presumably here you want to return a string
            // depending on the alert...
            return "" ;
        }, Platform::runLater).join();

        // ...
    }
};
...