Event-Driven Programming • Event: • A signal to the program that something has happened. • It can be triggered either by external user actions, such as mouse movements, button clicks, and keystrokes, or by the operating system, such as a timer. • The program can choose to respond to or ignore an event. • Source Object: • The component on which an event is generated is called the source object. • button, button click
A simple example • Write a program that display two buttons. OK and Cancel, in a window. A message is displayed on the console to indicate which button and when it is clicked
Listeners, Registrations, and Handling Events • An external user action on a source object triggers an event, and an listener receives the event. • The listener must implement the corresponding event-listener interface • The listener must be registered by the source object
Listener interface • Java provides a listener interface for every type of GUI event. • The listener interface is usually names XListener for XEvent, with excpetion of MouseMotionListener • For example, listener interface for ActionEvent is ActionListener • Each listener for ActionEvent should implement the ActionListener interface • The listener interface contains the methods, know as the handlers, which process the events
Registration • The listener object must be registered by the source object. Registration methods are dependent on the event type. For the ActionEvent, the method is addActionListener • In general, the method is named addXListener for the XEvent • ListenerClass lis = new ListenerClass(); • JButton jbt – new JButton(“OK”); • Jbt.addActionListener(lis);
Handling the Event • When you click the button, the JButton object generates an ActionEvent and passes it to invoke the actionPerformed method to handle the event • The event object contains information pertinent to the event type