JavaFX - Control and Concurrency

前端 未结 2 702
情话喂你
情话喂你 2021-01-15 04:43

I have a sample Hello World JavaFx. I am using Eclipse and eFxclipse plugin. My Eclipse is kepler which is Eclipse 4.3.2 version and Java servion is Jdk1.7-045.

Wh

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-15 05:11

    A Task is designed to interact with the ui on the fx-application thread, to take advantage of that support you should use it as designed :-)

    As a general rule, you must not access ui in the call method [*] of the Task. Instead, update one of its properties (message, progress ...) and bind that property to your ui. Sample code:

    Task taskWithBinding = new Task() {
        @Override 
        public Boolean call() {    
            final AtomicInteger i = new AtomicInteger(0);
            for( ; i.get() < 20; i.incrementAndGet()) {
                updateMessage("First row\nSecond row " + i);                      
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    return Boolean.FALSE;
                }
            }
            return Boolean.TRUE;               
        }        
    };           
    btn.textProperty().bind(taskWithBinding.messageProperty());
    

    [*] The one exception is outlined (wrap the access into an runLater) in the other answer. Doing so is technically correct - but then you are by-passing a Task's abilities and could use an arbitrary Runnable ...

提交回复
热议问题