Event-Driven Programming
Tags: java, programming, learning, beginners
Published: 2024-06-24 19:09:27

You can write code to process events such as a button click, mouse movement, and keystrokes. 

Suppose you wish to write a GUI program that lets the user enter a loan amount, annual interest rate, and number of years and click the _Calculate_ button to obtain the monthly payment and total payment, as shown in Figure below. How do you accomplish the task? You have to use _event-driven programming_ to write the code to respond to the button-clicking event.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/46zrsb9ddvaq3c30gkk0.png)

Before delving into event-driven programming, it is helpful to get a taste using a simple example. The example displays two buttons in a pane, as shown in Figure below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dfhbo80r22mjxi0ul4zn.png)

(a) The program displays two buttons. (b) A message is displayed in the
console when a button is clicked.

To respond to a button click, you need to write the code to process the button-clicking action. The button is an _event source object_—where the action originates. You need to create an object capable of handling the action event on a button. This object is called an _event handler_, as shown in Figure below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/63fbovjiy8cd3kohs9zh.png)

Not all objects can be handlers for an action event. To be a handler of an action event, two
requirements must be met:

1. The object must be an instance of the **EventHandler<T extends Event>** interface. This interface defines the common behavior for all handlers. **<T extends Event>** denotes that **T** is a generic type that is a subtype of **Event**.
2. The **EventHandler** object **handler** must be registered with the event source object using the method **source.setOnAction(handler)**.

The **EventHandler<ActionEvent>** interface contains the **handle(ActionEvent)** method for processing the action event. Your handler class must override this method to respond to the event. Listing 15.1 gives the code that processes the **ActionEvent** on the two buttons. When you click the _OK_ button, the message “OK button clicked” is displayed. When you click the _Cancel_ button, the message “Cancel button clicked” is displayed, as shown in Figure above (a) and (b).

```
package application;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;

public class HandleEvent extends Application {
	@Override // Override the start method in the Application
	public void start(Stage primaryStage) {
		// Create a pane and set its properties
		HBox pane = new HBox(10);
		pane.setAlignment(Pos.CENTER);
		Button btOK = new Button("OK");
		Button btCancel = new Button("Cancel");
		OKHandlerClass handler1 = new OKHandlerClass();
		btOK.setOnAction(handler1);
		CancelHandlerClass handler2 = new CancelHandlerClass();
		btCancel.setOnAction(handler2);
		pane.getChildren().addAll(btOK, btCancel);
		
		// Create a scene and place it in the stage
		Scene scene = new Scene(pane);
		primaryStage.setTitle("HandleEvent"); // Set the stage title
		primaryStage.setScene(scene); // Place the scene in the stage
		primaryStage.show(); // Display the stage
	}
	
	public static void main(String[] args) {
		Application.launch(args);
	}
}

class OKHandlerClass implements EventHandler<ActionEvent>{
	@Override
	public void handle(ActionEvent e) {
		System.out.println("OK button clicked");
	}
}

class CancelHandlerClass implements EventHandler<ActionEvent>{
	@Override
	public void handle(ActionEvent e) {
		System.out.println("Cancel button clicked");
	}
}

```

Two handler classes are defined in lines 37–42. Each handler class implements **EventHandler<ActionEvent>** to process **ActionEvent**. The object **handler1** is an instance of **OKHandlerClass** (line 19), which is registered with the button **btOK** (line 20). When the _OK_ button is clicked, the **handle(ActionEvent)** method (line 39) in **OKHandlerClass** is invoked to process the event. The object **handler2** is an instance of **CancelHandlerClass** (line 21), which is registered with the button **btCancel** in line 22. When the _Cancel_ button is clicked, the **handle(ActionEvent)** method (line 46) in **CancelHandlerClass** is invoked to process the event.

You now have seen a glimpse of event-driven programming in JavaFX.