Search code examples
javaeventsevent-dispatch-thread

In Java, Can I have a routine called every time the event-dispatch-thread returns from handling an input event?


I am working on a GUI, and I have a routine to update the display when things change underneath:

void update() {
    if (needsUpdating) {
        // ...
        needsUpdating = false;
    }
}

I'm trying to avoid calling update() "too often" -- ie, if many properties are set in succession I'd rather update() be called just once.

Is it possible to have update() called after every user input event -- key/mouse/etc? I could do this manually, but I have so many event handlers and I know I'll forget -- can Java do this for me?


Solution

  • yes, you can globally listen to user-events, though I wouldn't recommend it, except if you don't find another way:

    http://tips4java.wordpress.com/2009/08/30/global-event-listeners/

    The real problem seems to be your application design:

    I could do this manually, but I have so many event handlers and I know I'll forget

    try to model those "many" into separate parts and clearly define which part need to trigger an update at which time. Actually, there's no way around such a model, whatever the implementation of the actual listening, once you are beyond the most trivial of applications. For starters, see f.i.

    https://softwareengineering.stackexchange.com/questions/71022/what-is-good-programming-practice-for-structuring-java-project