Session 9 |
Introduction
The Before 7 material considered the basics of JavaFX programs, but one important part was left out there - event handling. Most GUI controls generate events that has to be handled. Event handling is a large part of any JavaFX application.
When we run a Java GUI program, the program interacts with the user, and the events set the program 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.
In JavaFX, an event is an instance of the javafx.event.Event
class or any subclass of Event
. JavaFX provides several events, including DragEvent
, KeyEvent
, TouchEvent
, and others. Every event includes the information about the event type, the event source and the event target.
Event types further classify the events of a single event class. For example, the KeyEvent
class contains the following event types: KEY_PRESSED
, KEY_RELEASED
, KEY_TYPED
. In the subtypes, the event type ANY is used to mean any event type in the event class. For example, to provide the same response to any type of key event, use KeyEvent.ANY
as the event type. To respond only when a key is released, use the KeyEvent.KEY_RELEASED
event type.
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 the buttonclicking action event. To respond to a button click, we need to write the code that processes the button-clicking action. We need to create an object capable of handling the action event on a button. This object is called an event handler.
Used resources:
Session 9 |