How to pause Thread while Alert runs within Platform.runLater - Javafx Java

Asked

Viewed 67 times

0

I need to execute a method within a Thread that contains Alert and Dialog. As you already know Javafx has the limitation of not being able to show Alert or Dialog inside a Thread, so I put them inside a Platform.runLater and it works, the problem is that while Alert is displayed Thread follows its flow. I would like the behavior to be the same when not using Thread, causing the flow to be paused while Alert is not closed. Would you be so kind as to help me ? Below excerpt from the sample code:

// Processa conteudo dentro da Task
public static void testeThread()
{
    Runnable task = new Runnable()
    {
        public void run()
        {
                System.out.println("inciando Thread, executa tarefas ");

                // *** Tratamento para alert/Dialog
                Platform.runLater(()-> 
                {
                    //Exibe mensagem ao usuario sobre bloqueio
                Alert alertLicencaInvalida = new Alert(Alert.AlertType.ERROR);
                alertLicencaInvalida.setTitle("Erro");
                alertLicencaInvalida.setHeaderText("Erro");
                alertLicencaInvalida.setContentText(" Ocorreu ");
                alertLicencaInvalida.showAndWait();
                // enquanto estiver aqui dentro, Thread deve ficar aguardando
                });
                // continuar Thread apos Alert for fechado
                System.out.println("Continuando Thread ");
            }
    };
    // Run the task in a background thread
    Thread backgroundThread = new Thread(task);
    // Terminate the running thread if the application exits
    backgroundThread.setDaemon(true);
    // Start the thread
    backgroundThread.start();
}

2 answers

1


The solution, taken from here, is to pause the thread using the communication resources between Java threads, in this case FutureTask:

System.out.println("inciando Thread, executa tarefas ");
String proximoTexto = lerDadosDeAlgumLugar();

if ("PROBLEMA".equals(proximoTexto)) {
    FutureTask<String> futureTask = new FutureTask(new AlertaDeErro());
    Platform.runLater(futureTask);
    proximoTexto = futureTask.get(); // vai pausar neste ponto
}

System.out.println("Continuando a thread...");

Alertdeerro.java

class AlertaDeErro implements Callable<String> {
    private TextField textField;

    @Override public String call() throws Exception {
        //Exibe mensagem ao usuario sobre bloqueio
        Alert alertLicencaInvalida = new Alert(Alert.AlertType.ERROR);
        alertLicencaInvalida.setTitle("Erro");
        alertLicencaInvalida.setHeaderText("Erro");
        alertLicencaInvalida.setContentText(" Ocorreu ");
        alertLicencaInvalida.showAndWait();
        return "Se eu quiser retornar alguma coisa para o thread, retorno aqui";
    }
}
  • Thank you @Piovezan your explanation has helped me a lot. I had already found the code you mentioned in the reply, but had failed to apply in my project.

0

Based on the @Piovezan explanation, I managed to apply the solution in my code. It follows full class to help future programmers:

    public class teste2 extends Application 
{
    public static void main(String[] args) 
    {
        Application.launch(args);
    }
    @Override
    public void start(Stage primaryStage) throws Exception 
    {
        testeThread();
    }
    public static void testeThread()
    {
        Runnable task = new Runnable()
        {
            public void run()
            {
                try
                {
                    System.out.println("inciando Thread, executa tarefas ");
                    boolean retornoAlert;
                    class AlertaDeErro implements Callable<Boolean>
                    {
                        @Override
                        public Boolean call() throws Exception
                        {
                            // Exibe mensagem ao usuario sobre bloqueio
                            Alert alertLicencaInvalida = new Alert(Alert.AlertType.ERROR);
                            alertLicencaInvalida.setTitle("Erro");
                            alertLicencaInvalida.setHeaderText("Erro");
                            alertLicencaInvalida.setContentText(" Ocorreu... ");
                            alertLicencaInvalida.showAndWait();
                            return true;
                        }
                    }
                    FutureTask<Boolean> futureTask = new FutureTask(new AlertaDeErro());
                    Platform.runLater(futureTask);
                    retornoAlert = futureTask.get(); // Para processamento da Thread e recebe retorno

                    // continuar Thread apos Alert for fechado
                    System.out.println("Continuando Thread "+ retornoAlert);
                } catch (InterruptedException ex) {
                    Logger.getLogger(teste2.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(teste2.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };
        // inicia Thread
        Thread backgroundThread = new Thread(task);
        backgroundThread.setDaemon(true);
        backgroundThread.start();
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.