Java Events

An event is defined as the change in the state of object. Java Events control the change in the state of object in GUI (Graphical User Interface) programming. Events occur when front end user interacts on GUI level of the system. For example, an event is generated when user clicks on a button, scrolls the page, moves the mouse or enters a character from keyboard, etc.

Types of Events

There are two main types of events in java programming language:

  • Foreground Events: The events that occur by user interaction on the GUI level are called Foreground events. For example, user click on a button, scrolling on the page, moving the mouse across the screen, entering a character from keyboard are Foreground events.
  • Background Events: The events that occur on the interaction of end user are called Background events. For example, hardware or software failure, time outs, operating system interrupts and operation completion are all background events.

Event Handling

The package  java.awt.event provides tools (classes, interfaces and listeners) to perform Java Events handling. User can perform various functions on the basis of events occurred. The table below shows the list of event classes and listener interfaces. These listener interfaces are used to apply different types of events.

Classes Listener Interfaces
ActionEventActionListener
AdjustmentEventAdjustmentListener
ComponentEventComponentListener
ContainerEventContainerListener
FocusEventFocusListener
ItemEventItemListener
KeyEventKeyListener
MouseEventMouseListener and MouseMotionListener
MouseWheelEventMouseWheelListener
TextEventTextListener
WindowEventWindowListener
Java Events

Define Action Event

When user clicks a button, selects a menu item or presses enter, then an action is performed. Programmer needs to set a frame to define the event. The method used is public void setSize().

Define Listener

In order to record the action, action listeners are used. For this ActionListener class is used. The method used to record the action is public void addActionListener(ActionListener a){}.

Registration Methods

The below table shows most commonly used registration methods. These registration methods register the component with the Listener. These methods are used to apply events.

Sr. No.ComponentMethod
1.Buttonpublic void addActionListener(ActionListener a){}
2.MenuItempublic void addActionListener(ActionListener a){}
3.TextFieldpublic void addActionListener(ActionListener a){}
4.TextFieldpublic void addTextListener(TextListener a){}
5.TextAreapublic void addTextListener(TextListener a){}
6.Checkboxpublic void addItemListener(ItemListener a){}
7.Choicepublic void addItemListener(ItemListener a){}
8.Listpublic void addActionListener(ActionListener a){}
9.Listpublic void addItemListener(ItemListener a){}
Java Events

The below program demonstrates the concept of java event handling.

// The file name is AwtControlExample.java
package com.tutorialsart.gui;

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

public class AwtControlExample {

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

   public AwtControlExample(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlExample  awtControlExample = new AwtControlExample();
      awtControlExample.showEventExample();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);                     // set dimensions of the frame
      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 showEventExample(){
      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());           // define click on OK button event
      submitButton.addActionListener(new ButtonClickListener());       // define click on Submit button event
      cancelButton.addActionListener(new ButtonClickListener());       // define click on Cancel button event

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

      mainFrame.setVisible(true);  
   }

   private class ButtonClickListener implements ActionListener{     // Using ActionListener interface
      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.");
         }  	
      }		
   }
}

In the above example, event is defined by setting the frame using the setLayout() method. An event is applied when user clicks on one of the buttons defined in the frame dimensions. The method addActionListener() records the action performed. Here, user has clicked on the OK button. So, the output of the above code after compilation and execution is:

Java Events