Thursday, May 30, 2019

java - How do event listeners constantly poll to check to see if a button, for example, was clicked?




How does, for example, a button in Java actually listen for an event to occur? I understand button events are handled once they are clicked in a special EDT (Event Dispatching Thread). But how without "busy waiting" does the button know that it has been actually clicked. The only way I understand this is possible if in a separate thread hidden from the user such as the Event Dispatching Thread there is a constant polling every so often, maybe every few milliseconds to check to see if it was clicked. On top of this, how does a button click invoke code?




I assume people are going to suggest it is the Observer Pattern at work here, but from the examples I have seen, the user more or less explicitly notifies the observers so it's almost no different than calling just a regular method.



s.setName("IceCream");
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers();
}



and then the update() method is called. This isn't the Observer Pattern from scratch but using the Observable and Observer classes.



Let me know if anything needs to be clarified



This question is sort-of-similar to my last question regarding how to constantly poll a condition without busy waiting. How do you pause a thread until a condition becomes true without busy waiting?


Answer




How does, for example, a button in Java actually listen for an event to occur?





The button doesn't do anything. The button only provides a handler (i.e., a java.awt.event.ActionListener) that the event dispatch thread (EDT) will call when it decides that a given mouse click is intended for that button.



It's the EDT that waits for mouse and keyboard events. How it waits will depend on what operating system is running it. Some operating systems provide a single system call that lets a process wait for input from any one of several different sources. Under Windows it's WaitForMultipleObjects(...). Under Linux, it's either select(...) or poll(...).



Given some hypothetical operating system that provides native threads, but no select()-like function, the JVM could create one thread for each different source of input (e.g., a keyboard thread, a mouse thread, ...) and these could all push events onto a queue that the EDT would consume.







I assume people are going to suggest it is the Observer Pattern at work here,





Basically, yes, but since Java is almost as old as the idea of named patterns, you might not find the word "observer" in the source code.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...