I am making an application where I have to periodically fetch satellite imagery (rather intensive), so I had to find a way to capture only the last event as well. I settled on spawning a thread to count down for some length of time before executing the intensive task and a resize-listener that resets the count. It seems more efficient to me than scheduling and unscheduling tasks hundreds of times.
Note I've also got some logic in here to capture the first window-size-change with System.currentTimeMillis();
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
public class ResizeListener implements ChangeListener {
long lastdragtime = System.currentTimeMillis();
double xi, yi, dx, dy, wid, hei;
GuiModel model;
TimerThread timebomb;
public ResizeListener(GuiModel model) {
this.model = model;
timebomb = new TimerThread(350);
timebomb.start();
}
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
if (System.currentTimeMillis() - lastdragtime > 350) { //new drag
xi = model.stage.getWidth();
yi = model.stage.getHeight();
model.snapshot = model.canvas.snapshot(null, null);
}
timebomb.active = true;//start timer
timebomb.ms = timebomb.starttime;//reset timer
wid = model.stage.getWidth()-72;
hei = model.stage.getHeight()-98;
dx = model.stage.getWidth() - xi;
dy = model.stage.getHeight() - yi;
if (dx < 0 && dy < 0) {
model.canvas.setWidth(wid);
model.canvas.setHeight(hei);
model.graphics.drawImage(model.snapshot, -dx/2, -dy/2, wid, hei, 0, 0, wid, hei);
} else if (dx < 0 && dy >= 0) {
model.canvas.setWidth(wid);
model.graphics.drawImage(model.snapshot, -dx/2, 0, wid, hei, 0, 0, wid, hei);
} else if (dx >= 0 && dy < 0) {
model.canvas.setHeight(hei);
model.graphics.drawImage(model.snapshot, 0, -dy/2, wid, hei, 0, 0, wid, hei);
}
lastdragtime = System.currentTimeMillis();
}
private class TimerThread extends Thread {
public final int starttime;//multiple of 25
public int ms = 0;
public boolean active = false;
public TimerThread(int starttime) {
this.setDaemon(true);
this.starttime = starttime;
}
public void run() {
while (true) {
try {
Thread.sleep(25);
} catch (InterruptedException x) {
break;
}
if (active) {
ms -= 25;
if (ms <= 0) {
active = false;
Platform.runLater(() -> {
model.canvas.setWidth(wid);
model.canvas.setHeight(hei);
model.fetchSatelliteImagery();
model.refresh();
});
}
}
}
}
}//end TimerThread class
}//end listener class