gpt4 book ai didi

java - 获取组件的最后一次调整大小事件

转载 作者:行者123 更新时间:2023-12-02 09:46:35 24 4
gpt4 key购买 nike

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

现在,我需要对调整大小事件进行一些昂贵的计算。如果这种情况经常发生,那就太多了。忽略大多数事件并仅对最后一个事件使用react(例如,如果用户释放鼠标按钮)是可以的。问题是,我不知道如何找出最后一次调整大小事件是什么。如果我采用天真的方法:

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

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

最后一次计算后,窗口的大小可能会调整得更多,因此计算将与正确的最终尺寸不匹配。

有什么好的解决方案吗?

最佳答案

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

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

关于java - 获取组件的最后一次调整大小事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17338322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com