Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

SWING event handling


May 15, 2021 SWING


Table of contents


SWING event handling

What is an event?

Changing the state of an object is called an event, which describes a state change at the source. E vents produce the result of the user interacting with the graphical user interface components. For example, clicking a button, moving the mouse, entering a character through the keyboard, selecting an item from a list, scrolling the page is all activities that cause an event to occur.

The type of event

Events can be broadly divided into two categories:

  • Fore desk events - These events require direct user interaction. T hey are the result of human interaction with graphical components in the graphical user interface. For example, click a button, move the mouse, enter a character through the keyboard, select an item from the list, scroll through the page, and so on.

  • Background events - These events require end-user interaction, and they are called background events. Operating system outages, hardware or software failures, timers out of date, and completion of operations are examples of background events.

What is event handling?

Event handling is a mechanism that controls an event when it occurs and determines what should happen. T his mechanism has code called an event handler that is executable when an event occurs. J ava uses the proxy event model to handle events. T he model defines a standard mechanism for generating and handling events. Let's briefly introduce this model.

The proxy event model has the following key actors, namely:

  • Source - The source is an object on which the event occurs. T he source is responsible for providing information about the event to its processor. Java provides the class of the source object.

  • Listener - It is also known as handling as an event. T he listener is responsible for generating a response to an event. F rom the perspective of the Java implementation, the listener is also an object. T he listener waits until it receives an event. Once the event is received, the event of the listener process returns.

The advantage of this approach is that the user interface logic is completely separate from the logic that generated the event. U ser interface elements can delegate the handling of events to a separate piece of code. I n this model, the listener needs to be registered with the source object so that the listener can receive event notifications. This is a valid way to handle events because these event notifications are sent only to listeners who want to receive them.

The steps involved in event handling

  • The user clicks the button and generates the event.

  • Now objects for event classes are automatically created, and information about sources and events is populated in the same object.

  • Event objects are forwarded to methods that register listener classes.

  • The method is now executed and returned.

Key points to keep in mind about listeners

  • In order to design a listener class, we must develop some listener interfaces. These listener interfaces predict some common abstract callback methods that must be implemented by the listener class.

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

Callback method

These methods are provided by the API provider, defined by the application operator, and called by the application developer. T he callback method here represents an event method. R esponding to an event java jre triggers a callback method. All of these callback methods are provided in the listener interface.

If a component needs some listener to listen to its events, the source must register itself with the listener.

Example of event handling

Use any editor of your choice to create the following Java program in D:/ > SWING > com > tutorialspoint > gui >

SwingControlDemo.java

package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingControlDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   public SwingControlDemo(){
      prepareGUI();
   }
   public 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() {
         public 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 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.");
         }      
      }     
   }
}

Use the command prompt to compile the program. G o to D:/ SWING and enter the command below.

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

If no error occurs, it means that the compilation was successful. Use the following command to run the program.

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

Verify the output below

SWING event handling