Serverside thread to refresh an image

I would like to have a Java Timer to update an image if a CheckBox is selected.

Checkbox refresh = new Checkbox("Automatic refresh");
Image image = new Image();
add(refresh, image);

Timer timer = new Timer("CameraUpdate");
timer.schedule(new ImageUpdate(), 0, 5000);

private class ImageUpdate extends TimerTask {
    @Override
    public void run() {
        try {
            getUI().get().access(() -> {
                image.setSrc("http://source/img.jpg?timestamp=" + System.currentTimeMillis());
            });
        } catch (Exception ex) {
            logger.error("Can't update image: {}", ex.getMessage());
        }
    }
}

But an error is thrown within the run. I think because there is no link between the Thread and the image.
How can this be done?

Thanks
Frank

Hi Frank,

You should capture the UI outside the body of run method; a solution may be using Attach/Detach event listener to capture UI, schedule and cancel the Timer.

Checkbox refresh = new Checkbox("Automatic refresh");
Image image = new Image();
add(refresh, image);

Timer timer = new Timer("CameraUpdate");

addAttachListener(event -> {
	UI ui = event.getUI();	
	timer.schedule(new ImageUpdate(ui), 0, 5000);	
});
addDetachListener(event -> timer.cancel());


private class ImageUpdate extends TimerTask {
    private final UI ui;
	ImageUpdate(UI ui) { this.ui = ui; }
    @Override
    public void run() {
        try {
            ui.access(() -> {
                image.setSrc("http://source/img.jpg?timestamp=" + System.currentTimeMillis());
            });
        } catch (Exception ex) {
            logger.error("Can't update image: {}", ex.getMessage());
        }
    }
}

HTH

Marco

Seems to be a perfect solution, thanks a lot Marco!