简体   繁体   中英

I don't understand what consume() does

I've been searching through Java's documentation to understand what consume does but I don't understand the explanation they provide.

For instance, a MouseEvent class contains the method consume(). Java documentation states that consume(): "consumes this event so that it will not be processed in the default manner by the source which originated it."

In the following paragraph they provide an example of what consume() does: Input events are delivered to listeners before they are processed normally by the source where they originated. This allows listeners and component subclasses to "consume" the event so that the source will not process them in their default manner. For example, consuming mousePressed events on a Button component will prevent the Button from being activated.

If I understand correctly, normally once an event like 'mousePressed' occurs on a Button component, the button should be activated. But by calling consume on the event the component (which contains a listener) won't respond since the event was consumed or destroyed before it even reached the component? Therefore the component won't even have a chance to process in the "default manner"?

Thank you for the help.

Basically, there could be a number of objects "listening" for that MouseEvent —and Java tells each one, in the reverse order that they were registered as listeners, that the event occurred.

By calling event.consume() , you're telling Java to stop telling the other listeners that the event happened—so if your listener is the first one to receive the event (eg, the last one to register for the event), no other listeners will know the MouseEvent even happened—including any that would be responsible for that button click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM