DEV Community

Cover image for Events and Event Sources
Paul Ngugi
Paul Ngugi

Posted on

Events and Event Sources

An event is an object created from an event source. Firing an event means to create an event and delegate the handler to handle the event.

When you run a Java GUI program, the program interacts with the user, and the events drive its execution. This is called event-driven programming. An event can be defined as a signal to the program that something has happened. Events are triggered by external user actions, such as mouse movements, mouse clicks, and keystrokes. The program can choose to respond to or ignore an event. The example in the preceding section gave you a taste of event-driven programming.

The component that creates an event and fires it is called the event source object, or simply source object or source component. For example, a button is the source object for a buttonclicking action event. An event is an instance of an event class. The root class of the Java event classes is java.util.EventObject. The root class of the JavaFX event classes is javafx.event.Event. The hierarchical relationships of some event classes are shown in Figure below.

Image description

An event object contains whatever properties are pertinent to the event. You can identify the source object of an event using the getSource() instance method in the EventObject class. The subclasses of EventObject deal with specific types of events, such as action events, window events, mouse events, and key events. The first three columns in Table below list some external user actions, source objects, and event types fired. For example, when clicking a button, the button creates and fires an ActionEvent, as indicated in the first line of this table. Here, the button is an event source object, and an ActionEvent is the event object fired by the source object, as shown in Figure below.

Image description

Image description

If a component can fire an event, any subclass of the component can fire the same type of event. For example, every JavaFX shape, layout pane, and control can fire MouseEvent and KeyEvent since Node is the superclass for shapes, layout panes, and controls.

Top comments (0)