English 中文(简体)
SWING - Event Handling
  • 时间:2024-12-22

SWING - Event Handpng


Previous Page Next Page  

In this chapter, you will learn about Events, its types, and also learn how to handle an event. Example is provided at the end of the chapter for better understanding.

What is an Event?

Change in the state of an object is known as Event, i.e., 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. For example, cpcking on a button, moving the mouse, entering a character through keyboard, selecting an item from the pst, and scrolpng the page are the activities that causes an event to occur.

Types of Event

The events can be broadly classified into two categories −

    Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, cpcking on a button, moving the mouse, entering a character through keyboard, selecting an item from pst, scrolpng the page, etc.

    Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events.

What is Event Handpng?

Event Handpng is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs.

Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.

The Delegation Event Model has the following key participants.

    Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it s handler. Java provide us with classes for the source object.

    Listener − It is also known as event handler. The pstener is responsible for generating a response to an event. From the point of view of Java implementation, the pstener is also an object. The pstener waits till it receives an event. Once the event is received, the pstener processes the event and then returns.

The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to a separate piece of code.

In this model, the pstener needs to be registered with the source object so that the pstener can receive the event notification. This is an efficient way of handpng the event because the event notifications are sent only to those psteners who want to receive them.

Steps Involved in Event Handpng

Step 1 − The user cpcks the button and the event is generated.

Step 2 − The object of concerned event class is created automatically and information about the source and the event get populated within the same object.

Step 3 − Event object is forwarded to the method of the registered pstener class.

Step 4 − The method is gets executed and returns.

Points to Remember About the Listener

    In order to design a pstener class, you have to develop some pstener interfaces. These Listener interfaces forecast some pubpc abstract callback methods, which must be implemented by the pstener class.

    If you do not implement any of the predefined interfaces, then your class cannot act as a pstener class for a source object.

Callback Methods

These are the methods that are provided by API provider and are defined by the apppcation programmer and invoked by the apppcation developer. Here the callback methods represent an event method. In response to an event, java jre will fire callback method. All such callback methods are provided in pstener interfaces.

If a component wants some pstener to psten ot its events, the source must register itself to the pstener.

Event Handpng Example

Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >

SwingControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

pubpc class SwingControlDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   pubpc SwingControlDemo(){
      prepareGUI();
   }
   pubpc static void main(String[] args){
      SwingControlDemo swingControlDemo = new SwingControlDemo();  
      swingControlDemo.showEventDemo();       
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         pubpc void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      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"); 

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

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

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

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

      mainFrame.setVisible(true);  
   }
   private class ButtonCpckListener implements ActionListener{
      pubpc void actionPerformed(ActionEvent e) {
         String command = e.getActionCommand();  
         
         if( command.equals( "OK" ))  {
            statusLabel.setText("Ok Button cpcked.");
         } else if( command.equals( "Submit" ) )  {
            statusLabel.setText("Submit Button cpcked."); 
         } else {
            statusLabel.setText("Cancel Button cpcked.");
         }  	
      }		
   }
}

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

D:AWT>javac com	utorialspointguiSwingControlDemo.java

If no error occurs, it means the compilation is successful. Run the program using the following command.

D:AWT>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output.

SWING  Event Handpng Advertisements