JavaFX 2 StringProperty does not update field until enclosing method returns

前端 未结 1 1693
旧时难觅i
旧时难觅i 2021-01-16 11:36

I would like to update a Label in a JavaFX application so that the text changes multiple times as the method runs:

private void analyze(){
    labelString.se         


        
1条回答
  •  一整个雨季
    2021-01-16 12:07

    Assuming you are invoking your analyze() method on the FX Application Thread (e.g. in an event handler), your time consuming code is blocking that thread and preventing the UI from updating until it is complete. As @glen3b says in the comments, you need to use an external thread to manage this code.

    JavaFX provides a Task API which helps you do this. In particular, it provides methods which invoke code on the Java FX Application thread for you, allowing you to update the UI safely from your background Task.

    So you can do something like

    private void analyze() {
        Task task = new Task() {
            public Void call() {
                updateMessage("Analyzing");
                // time consuming task here
                updateMessage("Analysis complete");
            }
        };
        labelString.bind(task.messageProperty());
        new Thread(task).start();
    }
    

    If you need to unbind the StringProperty when the task is complete, you can do

    task.setOnSucceeded(new EventHandler() {
        @Override
        public void handle(WorkerStateEvent event) {
            labelString.unbind();
        }
    });
    

    0 讨论(0)
提交回复
热议问题