frank.63
(Frank Delporte)
April 9, 2021, 12:11pm
1
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
mcollovati
(Marco Collovati)
April 12, 2021, 4:33pm
2
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
frank.63
(Frank Delporte)
April 12, 2021, 5:19pm
3
Seems to be a perfect solution, thanks a lot Marco!