ProgressBar in Javafx does not update in onAction block

前端 未结 2 1825
天命终不由人
天命终不由人 2020-11-29 11:04

I\'d like to have a progress bar that updates inside an onAction block. For some reason in the following code, the progress bar doesn\'t update until it exits

相关标签:
2条回答
  • 2020-11-29 11:32

    You are blocking the javafx event thread you need to do the work in another thread and sync back only the setProgress call with Platform.runLater

    0 讨论(0)
  • 2020-11-29 11:41

    Long form of tomsomtom's precise answer:

    If you use the JavaFX Thread to do this kind of long term work, you stop the UI from updating etc. So you have to run your worker in a sparate thread. If you run in a separate Thread, all GUI operatione like progress.setProgress() have to be passed back to the JavaFX Thread using runLater() as JavaFX is not multithreaded.

    Try this in your Action:

        submit.setOnAction( new EventHandler<ActionEvent>() {
            @Override
            public void handle( ActionEvent event ) {
                double size = 10.0;
                new Thread(){
                    public void run() {
                        for (double i = 0.0; i < size; i++){
                            final double step = i;
                            Platform.runLater(() -> progress.setProgress( step / size ));
                            System.out.printf("Complete: %02.2f%n", i * 10);
    
                            try {
                                Thread.sleep(1000); 
                            } catch(InterruptedException ex) {
                                Thread.currentThread().interrupt();
                            }
                        }
                    }
                }.start();
            }
    
        } );
    
    0 讨论(0)
提交回复
热议问题