Close

Java Swing - Coalescing (combining) high frequency events to improve performance

[Last Updated: Jul 5, 2018]

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();
      }
  }
}

Example Main

public class CoalesceEventExample {
  public static void main(String[] args) {
      JLabel displayLabel = new JLabel();
      JTextField inputField = new JTextField();
      addTextListener(inputField, displayLabel);
      JFrame frame = createFrame();
      frame.add(inputField, BorderLayout.NORTH);
      frame.add(displayLabel);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
  }

  private static void addTextListener(JTextField inputField, JLabel displayLabel) {
      CoalescedEventUpdater updater = new CoalescedEventUpdater(400, () -> {
          displayLabel.setText(inputField.getText());
      });
      inputField.getDocument().addDocumentListener(new DocumentListener() {
          @Override
          public void insertUpdate(DocumentEvent e) {
              update();
          }

          @Override
          public void removeUpdate(DocumentEvent e) {
              update();
          }

          @Override
          public void changedUpdate(DocumentEvent e) {
              update();
          }

          private void update() {
              updater.update();
          }
      });
  }

  private static JFrame createFrame() {
      JFrame frame = new JFrame("Coalesce Events Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(new Dimension(600, 300));
      return frame;
  }
}

Output

The 'displayLabel' will get updated only after when user has paused for 400ms while typing in the 'inputField'

Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.5.4

Java Swing - Coalescing Events Example Select All Download
  • swing-coalesced-events
    • src
      • main
        • java
          • com
            • logicbig
              • example
              • uicommon
                • CoalescedEventUpdater.java

    See Also