How are events generated in Java?

First of all, I am not asking about the Processing event . I know that processing is done using the Observer pattern.

Let me give you a small example. Suppose JButton has a JFrame. I click on this button. Now how does the button know that I clicked on it?

1) Is there any java thread to click on? If so, where does this code come from (wait until I get the link)? Then each swing component expects events on top of threads? I guess this is a very expensive task.

2) If not, how does it work?

+4
source share
3 answers

The observer pattern is used throughout the stack:

  • CPU,
  • , , .. . , ,
  • Swing " " :

    while (!shutdownRequested) {
        Event e = retrieveEventFromEventQueue(); // for instance our mouse clicked event
        handleEvent(e);
    }
    

    AWT/Swing , . , , handleEvent() . , ( , ui) , .

+1

- java ?

, java.awt.EventDispatchThread. java:

Swing , . , Swing, . , Swing "": . . Swing API "" ; . Swing . , , , .

,

, (, )?

EventDispatchThread pumpEvents(Conditional) run.

public void run() {
    try {
        pumpEvents(new Conditional() {
            public boolean evaluate() {
                return true;
            }
        });
    } finally {
        getEventQueue().detachDispatchThread(this);
    }
}

, ( EDT), pumpEvents(Conditional). , Conditional false, Event .

AWTEvent#getNextEvent, .

? , .

, java

, . - , ActionListener.actionPerformed. , invokeLater invokeAndWait. ; , .

java.awt.EventQueue. , .

private static final int LOW_PRIORITY = 0;
private static final int NORM_PRIORITY = 1;
private static final int HIGH_PRIORITY = 2;
private static final int ULTIMATE_PRIORITY = 3;

EventQueue, . .

, , PaintEvent.Paint, PaintEvent.UPDATE, MouseEvent.MOUSE_MOVED, MouveSevent.MOUSE_DRAGGED.

, .

+1

Is there any java thread to click on?

Yes, it's called the Event Dispatcher (EDT).

Since all Swing components are lightweight, which means just nice animation and nothing more, it really is a top-level component, say JFrame, that tracks mouse clicks and passes them to the component at that pixel.

0
source

Source: https://habr.com/ru/post/1584767/


All Articles