本文介绍了如何实现在Java Swing的空闲任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个越来越成为相当慢的GUI应用程序。我要开始为各种GUI任务的引入时机 - 然而,我们许多GUI操作的触发,然后后来援引触发其他动作等动作

最后,这一切都平息下来并没有什么更多的事情要做。在这个时候,我想停止一个计时器,并报告了多久了图形用户界面的行动了。

我想这样做的方式是实现一个名为 invokeOnceIdle(Runnable任务)方法。该方法将执行任务提供唯一的一次AWTEventQueue是空。即所提供的任务应该是在队列中的最后一件事。

要做到这将是一种方法是,如果有指定最低优先 SwingUtilities.invokeLater 的方式 - 但这是不可能的

我旁边看了看,如果我能的invokeLater一个Runnable进行检查,看是否该事件队列为空 - 但是有,看看事件队列实际上是空的没有公开的方式

什么是做到这一点的最好方法是什么?


解决方案

使用自己的事件队列,你可以很容易地实现这个目标。这里的东西,我做起来,应该让你去:

 私有静态类MyEventQueue扩展的EventQueue {    私人deque的<&的Runnable GT; onceIdle =新的LinkedList<&的Runnable GT;();    公共MyEventQueue(){
        。Toolkit.getDefaultToolkit()getSystemEventQueue()推(本);
    }    公共无效runOnceIdle(Runnable的托伦){
        onceIdle.addLast(托伦);
    }    @覆盖
    保护无效则dispatchEvent(AWTEvent中的事件){
        super.dispatchEvent(事件);
        如果(peekEvent()== NULL){
            对于(Runnable接口托伦:onceIdle){
                toRun.run();
            }
            onceIdle.clear();
        }
    }
}

所有你需要做的就是把你的空闲一旦可运行使用的EventQueue实例 runOnceIdle()

I have a GUI app that is getting to be quite slow. I want to start introducing timing for various GUI tasks - however, many of our GUI actions trigger other actions which then "invoke later" to trigger other actions.

Eventually, it all settles down and there's nothing more to do. At this time, I want to stop a timer and report how long that GUI "action" took.

I figured the way to do this is to implement a method called invokeOnceIdle(Runnable task). The method will execute the supplied task only once the AWTEventQueue is "empty". i.e. the supplied "task" should be the last thing in the queue.

One way to do this would be is if there's a way to specify a "lowest" priority to SwingUtilities.invokeLater - but this isn't possible.

I next looked to see if I could "invokeLater" a Runnable which checks to see if the event queue is "empty" - but there's no public way to see if the event queue is actually empty.

What's the best way to do this?

解决方案

Using your own event queue, you can easily reach that goal. Here something that I cooked up and should get you going:

private static class MyEventQueue extends EventQueue {

    private Deque<Runnable> onceIdle = new LinkedList<Runnable>();

    public MyEventQueue() {
        Toolkit.getDefaultToolkit().getSystemEventQueue().push(this);
    }

    public void runOnceIdle(Runnable toRun) {
        onceIdle.addLast(toRun);
    }

    @Override
    protected void dispatchEvent(AWTEvent event) {
        super.dispatchEvent(event);
        if (peekEvent() == null) {
            for (Runnable toRun : onceIdle) {
                toRun.run();
            }
            onceIdle.clear();
        }
    }
}

All you have to do is push your "Once idle" runnables to the instance of the EventQueue using runOnceIdle()

这篇关于如何实现在Java Swing的空闲任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:50