我正在制作一个应用程序,我必须定期获取卫星图像(相当密集),所以我必须找到一种方法来仅捕获最后一个事件。我决定在执行密集任务和重置计数的调整大小侦听器之前生成一个线程以倒计时一段时间。对我来说,这似乎比数百次安排和取消安排任务更有效率。
注意我在这里也有一些逻辑来捕捉第一个窗口大小的变化 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