Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How events are generated in Java?

Tags:

java

events

swing

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?

like image 881
DesirePRG Avatar asked Sep 29 '22 03:09

DesirePRG


1 Answers

The observer pattern is used throughout the entire stack:

  1. The user releases the mouse button
  2. The mouse sends a message to the CPU, which triggers a hardware interrupt
  3. The operating system's interrupt handler realizes that the mouse has not been moved since the button was pressed, i.e. that a mouse click occured. It identifies the window at the mouse position, and the application responsible for that window, and puts a mouse-clicked message into the application's event queue
  4. 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.

like image 78
meriton Avatar answered Oct 25 '22 17:10

meriton