我有一个eclipse e4应用程序。我正在尝试在调整窗口大小时运行一些代码xyz()
。问题是,调整resize侦听器的大小时会多次调用,而我想在用户调整大小后只调用xyz()
一次。我能想到的唯一方法是在窗口本身捕获mouseUp事件,但是无法找到API来获得相同的信息。
示例代码
public class CTGHandler{
@Execute
public void execute(final EPartService partService, final EModelService modelService){
MPart mPart = modelService.createModelElement(MPart.class);
mPart.setLabel("CTGLive"); //$NON-NLS-1$
mPart.setContributionURI("bundleclass://test.ui.ctg/test.ui.ctg.CTGPart"); //$NON-NLS-1$
partService.showPart(mPart, PartState.ACTIVATE);
}
}
public class CTGPart {
@Inject
private IEventBroker eventBroker;
@Inject
public CTGPart(){
//Do something here...
}
@PostConstruct
public void init(final Composite parent){
Composite grandParent = parent.getParent().getParent().getParent();
System.out.println(grandParent); //Prints "Shell {CTGApp}"
grandParent.addControlListener(new ControlListener() {
@Override
public void controlResized(ControlEvent e){
System.out.println(e); // Prints "ControlEvent{Shell {CTGApp} time=9286942 data=null}" multiple times for a single resize event
// because there is no way the framework can understand if the resize was complete
xyz();// called each time, but I want this to be called only once
}
@Override
public void controlMoved(ControlEvent e)
{}
});
// MouseUp event on the application window so that xyz(); can be called once and we can get rid of grandParent.addControlListener(){...}
}
}
答案 0 :(得分:2)
您可能会发现最好使用ScheduledFuture和ScheduledExecutorService推迟处理调整大小事件。
如果您保留对Future的引用,您可以取消之前的引用并安排新的引用。这样,您可以将在短时间内触发的许多事件折叠为单个稍微延迟的事件。您需要选择一个良好的延迟时间来平衡将被吞下的事件数量与最后一次调度后的延迟。
grandParent.addControlListener(new ControlListener() {
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(1);
ScheduledFuture scheduledFuture;
@Override
public void controlResized(ControlEvent e){
if(scheduledFuture != null) {
scheduledFuture.cancel();
}
scheduledFuture = scheduledExecutorService.schedule(new Callable() {
public Object call() throws Exception {
xyz();
return null;
}
}, 1, TimeUnit.SECONDS);
}
@Override
public void controlMoved(ControlEvent e)
{}
});
如果您收到很多活动,您应该创建一个静态Callable,而不是每次都创建一个新的。