Following example provides a utility for coalescing multiple high frequency events into a single update event. This can be useful in scenarios where user action generates a series of events (like typing in a field, moving windows etc) and we will like to process a costly operation only at the end of that.
Example
package com.logicbig.uicommon;
import javax.swing.*;
public class CoalescedEventUpdater {
private Timer timer;
public CoalescedEventUpdater(int delay, Runnable callback) {
timer = new Timer(delay, e -> {
timer.stop();
callback.run();
});
}
public void update() {
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(() -> {timer.restart();});
} else {
timer.restart();
}
}
}