Modifying JavaFX gui from different thread in different class

前端 未结 1 617
夕颜
夕颜 2020-12-21 10:46

I am trying to create an environment, in which a GUI is set up, and while the user is modifying its components through listeners, another thread is adding new elements to it

相关标签:
1条回答
  • 2020-12-21 11:13

    You can still use your standalone class.

    The rule is that changes to the UI must happen on the FX Application Thread. You can cause that to happen by wrapping calls from other threads that change the UI in Runnables that you pass to Platform.runLater(...).

    In your example code, d.addElement(i) changes the UI, so you would do:

    class Thread2 implements Runnable {
        private DifferentThreadJavaFXMinimal d;
    
        Thread2(DifferentThreadJavaFXMinimal dt){
            d=dt;
        }
    
        @Override
        public void run() {
            for (int i=0;i<4;i++) {
                final int value = i ;
                Platform.runLater(() -> d.addElement(value));
                // presumably in real life some kind of blocking code here....
            }
            System.out.println("Hahó");
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题