Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the last resize event of a component

Tags:

java

swing

resize

when using a ComponentListener to get notified of resize events, one can get a lot of events if the user drags the window corner to a new size.

Now, I need to do some expensive calculations on a resize event. That would be too much, if these occur that often. It would be OK to ignore most of the events and only react to the last one (if the user releases the mouse button, for example). The problem is, I do not know how to find out what the last resize event was. If I do the naive aproach:

this.addComponentListener(new ComponentAdapter() {
  @Override
  public void componentResized(final ComponentEvent e) {
    if (calculationInProgress){
      return;
    }

    calculationInProgress= true;
    doExpensiveCalculation();
    calculationInProgress= false;        
  }
});

it can happen that the window is resized even more after the last calculation and therefore the calculation wouldn't match the correct final dimensions.

What would a good solution to this?

like image 520
radlan Avatar asked Nov 03 '22 19:11

radlan


1 Answers

Here's a simple example of the Timer-based solution discussed in the comments:

package mcve;

import java.awt.event.*;
import javax.swing.*;

public abstract class ComponentResizeEndListener
extends    ComponentAdapter
implements ActionListener {

    private final Timer timer;

    public ComponentResizeEndListener() {
        this(200);
    }

    public ComponentResizeEndListener(int delayMS) {
        timer = new Timer(delayMS, this);
        timer.setRepeats(false);
        timer.setCoalesce(false);
    }

    @Override
    public void componentResized(ComponentEvent e) {
        timer.restart();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        resizeTimedOut();
    }

    public abstract void resizeTimedOut();
}

And then:

comp.addComponentListener(new ComponentResizeEndListener() {
    @Override
    public void resizeTimedOut() {
        doExpensiveCalculation();
    }
});
like image 180
Radiodef Avatar answered Nov 15 '22 12:11

Radiodef