Skip to content

Instantly share code, notes, and snippets.

@bonifaido
Last active December 12, 2015 06:38
Show Gist options
  • Save bonifaido/4730107 to your computer and use it in GitHub Desktop.
Save bonifaido/4730107 to your computer and use it in GitHub Desktop.
Good for autocompletion/searching
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class DelayedDocumentListener implements DocumentListener {
private final Timer timer;
private DocumentEvent lastEvent;
public DelayedDocumentListener(DocumentListener delegate) {
this(delegate, 500);
}
public DelayedDocumentListener(final DocumentListener delegate, int delay) {
timer = new Timer(delay, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timer.stop();
if (lastEvent.getType() == DocumentEvent.EventType.INSERT) {
delegate.insertUpdate(lastEvent);
} else if (lastEvent.getType() == DocumentEvent.EventType.REMOVE) {
delegate.removeUpdate(lastEvent);
} else {
delegate.changedUpdate(lastEvent);
}
}
});
}
private void storeUpdate(DocumentEvent e) {
lastEvent = e;
timer.restart();
}
@Override
public void insertUpdate(DocumentEvent e) {
storeUpdate(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
storeUpdate(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
storeUpdate(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment