Multi-Threading error when binding a StringProperty

前端 未结 1 1147
-上瘾入骨i
-上瘾入骨i 2020-12-20 18:28

I have a question about multi-threading and the binding of a StringProperty.

I have a class CacheManager, which contains a Thread which upd

1条回答
  •  醉梦人生
    2020-12-20 18:41

    It is wrong to call code that results in changes to the UI from a thread other than the FX Application Thread, regardless of whether or not it throws an exception. The FX toolkit makes a best effort to throw an exception if you violate this rule, but in some cases the effect on performance is too great to perform the check. If you create these bindings, then any subsequent changes to the properties to which you have bound must be executed on the FX Application Thread. I.e., if you are running in a background thread, you must change the properties with code like:

    Platform.runLater(() -> CacheManager.progress.set(...));
    

    and

    Platform.runLater(() -> CacheManager.status.set(...));
    

    Since you probably don't want your service code to be tied to JavaFX (via the Platform class), you could consider using listeners instead of bindings, and scheduling the updates from the listeners:

    CacheManager.progress.addListener((obs, oldValue, newValue) -> 
        Platform.runLater(() -> progressBar.setProgress(newValue.doubleValue())));
    CacheManager.status.addListener((obs, oldStatus, newStatus) -> 
        Platform.runLater(() -> someLabel.setText(newStatus)));
    

    If you replace the bindings with these listeners, then you are free to update the properties on any thread.

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