获取组件的最后一个调整大小事件 [英] Getting the last resize event of a component

查看:49
本文介绍了获取组件的最后一个调整大小事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 ComponentListener 获取调整大小事件的通知时,如果用户将窗口角拖动到新大小,则可以获得很多事件.

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.

有什么好的解决办法?

推荐答案

以下是评论中讨论的基于 Timer 的解决方案的简单示例:

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

然后:

comp.addComponentListener(new ComponentResizeEndListener() {
    @Override
    public void resizeTimedOut() {
        doExpensiveCalculation();
    }
});

这篇关于获取组件的最后一个调整大小事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆