What is Event handling in java?

Before understanding event handling, let’s understand what is events. In java, an event is an object which specifies the change of state in the source. It occurs whenever an action takes place. For example, clicking on a button, moving the mouse so on. There are two types of events.

Types of event

The events can be broadly classified into two categories as below:

  • Foreground Events – Those events require the direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example
  1.  Clicking on a button
  2. Moving the mouse
  3. Entering a character through the keyboard
  4. Selecting an item from the list
  5. Scrolling the page, etc.
  • Background Events – Those events that require the interaction of the end-user are known as background events. Operating system interrupts, hardware or software failure, the timer expires, an operation completion is the example of background events.

Event Handling

To handle the generated events, Java provides us several classes and interfaces. It controls the events and decides what should happen if an event occurs.

Here are some Event handling terminology:

EventsDescription
Event An event is a signal to the program that something happened.
Is can b triggered by typing in a text field, selecting an item etc. It handled by a piece of the code inside the program and the action initiated outside the scope of the program.
Event handlerThe cade that performs a task in response to an event in called event handler.
Event handling The process of responding to event that can occur at any time during execution of a program.
Event SourceIt is the object which generate event. It can be a button or any other component that the user can click. Event source accept registration, get the event from the user and call the listener’s event handling method.
Event listenerEvents generated by event source are sent to event listeners and handle them when they occur. In other word , event listener is basically a consumer that receives events from the source.
Event interfaceIt is an interface Which contains methods that the listener must implement and the source of the event invokes when the event occurs.
event handing in java

Event handling steps

1 The user click the button and event generates.
2 Now the object of the concerned event class is created automatically. And information about the source and the events get to populate within the same object
3 Event object forwards to the method of registered listener class.
4 The method is now get executed and returns.

For example

Create the following java program using any editor of your choice in say D:/ > AWT > com > mywork > gui > .

package com.Mywork.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showEventDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showEventDemo(){
      headerLabel.setText("Control in action: Button"); 

      Button okButton = new Button("OK");
      Button submitButton = new Button("Submit");
      Button cancelButton = new Button("Cancel");

      okButton.setActionCommand("OK");
      submitButton.setActionCommand("Submit");
      cancelButton.setActionCommand("Cancel");

      okButton.addActionListener(new ButtonClickListener()); 
      submitButton.addActionListener(new ButtonClickListener()); 
      cancelButton.addActionListener(new ButtonClickListener()); 

      controlPanel.add(okButton);
      controlPanel.add(submitButton);
      controlPanel.add(cancelButton);       

      mainFrame.setVisible(true);  
   }

   private class ButtonClickListener implements ActionListener{
      public void actionPerformed(ActionEvent e) {
         String command = e.getActionCommand();  
         if( command.equals( "OK" ))  {
            statusLabel.setText("Ok Button clicked.");
         }
         else if( command.equals( "Submit" ) )  {
            statusLabel.setText("Submit Button clicked."); 
         }
         else  {
            statusLabel.setText("Cancel Button clicked.");
         }  	
      }		
   }
}

Compile the program using the command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error, comes that means compilation is successful. Run the program using the following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo 

As a Result output

event handing in java

Recommended Post:

Convert java object into a JSON

Difference between the Java and JavaScript

How are java objects stored in memory?

Reference:

tutorialspoint.com

Leave a Comment