Select Page

An event is an action that takes place within a program, such as the clicking of a button.  Event is a change in the state of an object. That is, the event describes the change in the state of the source. Events are generated as a result of user interaction with the graphical user interface components. Examples include moving the mouse, clicking a mouse button etc.

When an event takes place, the component that is responsible for the event creates an event object in memory. The event object contains information about the event. The component that generated the event object is called the event source.

For example, when a user clicks a button, the JButton component generates an event object. The JButton component that generated the event object is called the event source

If the source component, that is the JButton, is connected to an event listener, the event object is automatically passed as an argument to a specific method in the event listener. The method then performs any actions that it was programmed to perform in response to the event. This process is referred to as event firing.

When you write a GUI application, you have to write event listeners for all the possible events that can be created by the components in the application.

Program to demonstrate event handling of a JButton

Output

JButton Event Handling

After clicking on the button, an action event is generated. This causes the private inner class, ButtonListener to run setting the content pane of the JFrame object to red.

JButton Event Handling2