First of all I am not asking about Event Handling. I know handling is implemented using the Observer pattern.
Let me take a small example. Suppose I have a Jbutton on a JFrame. I click on top of this button. Now how does the button know that I have clicked it?
1) Is there any java thread waiting for the click? If so from where does this code come from (wait till I get clicked part)? Then Does each and every swing component is waiting for events on top of threads? I assume this is a very expensive task.
2) If not, how does this work?
The observer pattern is used throughout the entire stack:
Our Swing application's "event dispatch thread" runs a loop of the form:
while (!shutdownRequested) {
Event e = retrieveEventFromEventQueue(); // for instance our mouse clicked event
handleEvent(e);
}
In AWT / Swing, there is single thread executing that code. The first call will block until a new event becomes available, and handleEvent() will call the listeners for this event. That is, a single thread performs all UI updates (which is why long-running tasks should not be done in event listeners, as this freezes the ui), and is sleeping if the user does not interact with the application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With