Luca Fülbier Luca Fülbier - 15 days ago 6
Java Question

JavaFX - Calling GUI methods from a different thread

I am writing an application that maps eyetracking data to an image that is displayed to the user. To make sure the GUI doesn't freeze i do the eyetracking data polling, mapping and other calculations in a separate

Task
.

The problem i am facing is, that for mapping screen coordinates to my displayed image, i have to call
Node.screenToLocal(x,y)
. How can i make these calls without violating thread-safety?

Answer

Use a AnimationTimer to do this call:

Task<Point2D> task = new Task<Point2D>() {

    @Override
    protected Point2D call() throws Exception {
        while (!isCancelled()) {
            Point2D eyePos = getEyePos();
            updateValue(eyePos);
        }
    }

};

AnimationTimer animation = new AnimationTimer() {

    @Override
    public void handle(long now) {
        Point2D point = task.getValue();
        if (value != null) {
            Point2D pointOnScreen = node.screenToLocal(point);

            // TODO: use result
        }
    }

};
animation.play();