How to insert an event to the beginning of Event Dispatch Thread queue in java?

前端 未结 3 2102
忘掉有多难
忘掉有多难 2021-02-20 00:45

I already know how Event Dispatch thread works. If there be short and long events in Event Dispatch thread like below, the application can\'t be responsive.

<
3条回答
  •  后悔当初
    2021-02-20 01:13

    You can create and use your own Event Queue that inserts new events in the way you want it. See the code snippet below how to setup a custom Event Queue:

    public class QueueTest {
        public static void main(String[] args) throws InterruptedException, InvocationTargetException {
            EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
            eventQueue.push(new MyEventQueue());
    
            EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    System.out.println("Run");
                }
            });
        }
    
        private static class MyEventQueue extends EventQueue {
            public void postEvent(AWTEvent theEvent) {
                System.out.println("Event Posted");
                super.postEvent(theEvent);
            }
        }
    }
    

    Your custom Event Queue could then post specific events that you want to be prepended to the queue with the highest priority. This might not ensure that it is the next event to be processed, but would probably fit best into the existing design.

提交回复
热议问题