Events, Event Sources, and Event Listeners
User interface events include key presses, mouse moves, button clicks, and so on
Most programs don't want to be flooded by boring events
A program can indicate that it only cares about certain specific events
Event listener:
Notified when event happens
Belongs to a class that is provided by the application programmer
Its methods describe the actions to be taken when an event occurs
A program indicates which events it needs to receive by installing event listener objects
Event source:
Event sources report on events
When an event occurs, the event source notifies all event listeners
Example: Use JButton components for buttons; attach an ActionListener to each button
ActionListener interface:
public interface ActionListener
{
void actionPerformed(ActionEvent event);
}
Need to supply a
class whose
actionPerformed method
contains instructions to be executed when button is clicked
event
parameter contains details about the event, such as the
time at which it occurred
Construct an
object of the listener and add it to the button:
ActionListener
listener = new ClickListener();
button.addActionListener(listener);
Which objects are the event source and the event listener in the ButtonViewer program?
Answer: The button object is the event source. The listener object is the event listener.
Why is it legal to assign a ClickListener object to a variable of type ActionListener?
Answer: The ClickListener class implements the ActionListener interface.