Event Handling in Java Swing

Event handling in Java Swing application is the process of capturing and responding to events that occur within the application. An event is an action or occurrence that takes place during program execution, such as a button click, mouse movement, or keyboard press. Java provides a rich set of APIs for event handling, including classes and interfaces for creating event listeners and handling different types of events.

The basic steps involved in event handling in Java swing applications are as follows:

  1. Define an event listener: An event listener is an object that is notified when an event occurs. In Java, event listeners are defined as interfaces that extend the java.util.EventListener interface. Each event listener interface includes one or more methods that define how the listener should respond to specific types of events.
  2. Register the event listener: Once an event listener interface has been defined, it must be registered with the component that will generate the events. This is typically done using the addXXXListener() method of the component, where XXX is the type of event being handled.
  3. Implement the event handling code: When an event occurs, the appropriate listener method is called, and the listener object can respond to the event by executing the appropriate code.

Following is an example of event handling in Java swing application using a button click event:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class EventHandelingDemo extends JFrame implements ActionListener {
	JButton myButton;

	public EventHandelingDemo() {
		myButton = new JButton("Click me!");

	public void actionPerformed(ActionEvent e) {
		System.out.println("Button clicked!");

	public static void main(String[] args) {
		EventHandelingDemo demo = new EventHandelingDemo();
		demo.setSize(200, 200);

In the example above, a button is created and added to the frame. An action listener is registered with the button using the addActionListener() method, and the actionPerformed() method is implemented to respond to the button click event by printing a message to the console. When the user clicks the button, the actionPerformed() method is called, and the message “Button clicked!” is printed to the console.