Question:
Event handling in Java?
xìn xīn
2008-02-14 11:22:39 UTC
Well, I have learned that their are at least 3 objects in a typical event-driven program: event object, event listener, and event source. Can someone give me an exmaple of each? I have also learned that an event object is hidden but I am having trouble understanding why that is!

Thanks in advance!
Four answers:
General Cucombre
2008-02-14 16:57:57 UTC
Here's simple example:



.....

JButton okButton;

.....

ActionListener listener = new ActionListener() {

public void actionPerformed(ActionEvent event) {

JOptionPane.showMessageDialog(null, "Hello");

}

}

okButton.addActionListener( listener );





'button' (okButton) is event source - it is the entity that generates the event when the user presses it.



'event' is event object - it is the object which describes the event itself (i.e. coordinates on the screen where the click occured) as well as the event source (button in this example).



'listener' is event listener - it is the object that takes action in response to an event. When listener is registered, Java framework invokes specific method of that listener object (actionPerformed in this case) and passes the event to it.



As far as the event object being hidden, it's not clear what this refers to. It is definitely not hidden from the listener itself.
rwid
2008-02-14 11:30:18 UTC
No quite, you are able to inspect event objects but they flow through the system very quickly (maybe that's what is meant by "hidden"). Event objects are a type of message. An event listener is the actual Java code that will react to an event object once registered to listen. The event source could be something like the keyboard, mouse (e.g. click, x-y movement) or a timer.



Therefore, some event source generates an event object and an action is taken by an event listener. Example: Left-mouse click generates several mouse-related events (e.g. down, up, double-click detection, with keyboard shift-key, etc.) which can be detected by a registered listener that executes a custom action such as to draw a pixel at the current x/y coordinates.
Tasm
2008-02-14 11:30:52 UTC
The object are things you see on the screen like a button.

You can add an event listener to the object, such as mouse event listener.

When the event happens to the object you can have code to do stuff.
binaryFusion
2008-02-14 11:35:31 UTC
Read the following answer by me. Then mail me if u have further questions.



https://answersrip.com/question/index?qid=20071208072721AA9EF3f&show=7#profile-info-189259d4bbb0dff1db9ddbf946b696ecaa


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...