Event Handling in Java with Example

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.

Components of Event Handling 

Event handling has three main components, 

  • Events:  An event is a change in state of an object. 
  • Events Source: An event source is an object that generates an event. 
  • Listeners:  A listener is an object that listens to the event. A listener gets notified when an event occurs. 

How areEvents  handled? 

A source produces an event and sends it with the source to one or more listeners. Once the listener receives the event, the event will be processed and returned. Many Java packages, such as java.util, java.awt and java.awt.event, support events. 

Important Event Classes and Interface 

Event ClassesDescriptionListener Interface
ActionEventgenerated when button is pressed, menu-item is selected, list-item is
double clicked
ActionListener
MouseEventgenerated when mouse is dragged, moved,clicked,pressed or
released and also when it enters or exits a component
MouseListener
KeyEventgenerated when input is received from keyboardKeyListener
ItemEventgenerated when check-box or list item is clickedItemListener
TextEventgenerated when value of textarea or textfield is changedTextListener
MouseWheelEventgenerated when mouse wheel is movedMouseWheelListener
WindowEventgenerated when window is activated, deactivated, deiconified,
iconified, opened or closed
WindowListener
ComponentEventgenerated when component is hidden, moved, resized or set visibleComponentEventListener
ContainerEventgenerated when component is added or removed from containerContainerListener
AdjustmentEventgenerated when scroll bar is manipulatedAdjustmentListener
FocusEventgenerated when component gains or loses keyboard focusFocusListener

Example of Event Handling

import java.awt.*; 
import java.awt.event.*; 
import java.applet.*; 
import java.applet.*; 
import java.awt.event.*; 
import java.awt.*; 
public class Test extends Applet implements KeyListener 
{ 
String msg=""; 
public void init() 
{ 
    addKeyListener(this); 
} 
public void keyPressed(KeyEvent k) 
{ 
   showStatus("KeyPressed"); 
} 
public void keyReleased(KeyEvent k) 
{ 
    showStatus("KeyRealesed"); 
} 
public void keyTyped(KeyEvent k) 
{ 
msg = msg+k.getKeyChar(); 
  repaint(); 
} 
public void paint(Graphics g) 
{ 
    g.drawString(msg, 20, 40); 
  } 
} 

HTML code :

<applet code="Test" width=300, height=100> 
</applet> 
Example of Event Handling

Steps to handle events: 

  • Implement appropriate interface in the class. 
  • Register the component with the listener. 

Registration Methods

For registering the component with the Listener, many classes provide the registration methods. For example:

  • Button
    • public void addActionListener(ActionListener a){}
  • MenuItem
    • public void addActionListener(ActionListener a){}
  • TextField
    • public void addActionListener(ActionListener a){}
    • public void addTextListener(TextListener a){}
  • TextArea
    • public void addTextListener(TextListener a){}
  • Checkbox
    • public void addItemListener(ItemListener a){}
  • Choice
    • public void addItemListener(ItemListener a){}
  • List
    • public void addActionListener(ActionListener a){}
    • public void addItemListener(ItemListener a){}

Java Event Handling Code

We can put the event handling code into one of the following places:

  1. Within class

  2. Other class

  3. Anonymous class

1) Java event handling by implementing ActionListener (Within class)

import java.awt.*;  
import java.awt.event.*;  
class AEvent extends Frame implements ActionListener{  
TextField tf;  
AEvent(){  
  
//create components  
tf=new TextField();  
tf.setBounds(60,50,170,20);  
Button b=new Button("click me");  
b.setBounds(100,120,80,30);  
  
//register listener  
b.addActionListener(this);//passing current instance  
  
//add components and set size, layout and visibility  
add(b);add(tf);  
setSize(300,300);  
setLayout(null);  
setVisible(true);  
}  
public void actionPerformed(ActionEvent e){  
tf.setText("Welcome");  
}  
public static void main(String args[]){  
new AEvent();  
}  
}  

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the position of the component it may be button, textfield etc.

Java event handling by implementing ActionListener (Within class)

2) Java event handling by outer class

import java.awt.*;  
import java.awt.event.*;  
class AEvent2 extends Frame{  
TextField tf;  
AEvent2(){  
//create components  
tf=new TextField();  
tf.setBounds(60,50,170,20);  
Button b=new Button("click me");  
b.setBounds(100,120,80,30);  
//register listener  
Outer o=new Outer(this);  
b.addActionListener(o);//passing outer class instance  
//add components and set size, layout and visibility  
add(b);add(tf);  
setSize(300,300);  
setLayout(null);  
setVisible(true);  
}  
public static void main(String args[]){  
new AEvent2();  
}  
}  
import java.awt.event.*;  
class Outer implements ActionListener{  
AEvent2 obj;  
Outer(AEvent2 obj){  
this.obj=obj;  
}  
public void actionPerformed(ActionEvent e){  
obj.tf.setText("welcome");  
}  
}  

3) Java event handling by anonymous class

import java.awt.*;  
import java.awt.event.*;  
class AEvent3 extends Frame{  
TextField tf;  
AEvent3(){  
tf=new TextField();  
tf.setBounds(60,50,170,20);  
Button b=new Button("click me");  
b.setBounds(50,120,80,30);  
  
b.addActionListener(new ActionListener(){  
public void actionPerformed(){  
tf.setText("hello");  
}  
});  
add(b);add(tf);  
setSize(300,300);  
setLayout(null);  
setVisible(true);  
}  
public static void main(String args[]){  
new AEvent3();  
}  
}  

Java Abstract Window Toolkit(AWT) 

AWT includes a big amount of classes and techniques to build and handle apps such as windows, buttons, scroll bars, etc. The AWT was intended to provide a prevalent collection of GUI design instruments capable of working on a multitude of platforms.The tools supplied by the AWT are introduced using the indigenous GUI toolkit of each platform, thus maintaining each platform’s look and feel. This is an benefit of using AWT.But the disadvantage of such an strategy is that when displayed on another platform, GUI built on one platform may look distinct. 

AWT is the basis for Swing, i.e. Swing is a set of GUI interfaces that extend the AWT. But nowadays AWT is merely used as most GUI Java programs are being implemented using Swing, due to its rich implementation of GUI controls and lightweight nature. 

 

Java AWT Hierarchy 

Java AWT Hierarchy

  • Component class 

At the top of the AWT hierarchy is the component category. Component is an abstract class encapsulating all the visual component characteristics. Recalling the present foreground and background colors and the presently chosen text font is accountable for a component item. 

  • Container 

Container is an AWT element containing a different element such as button, text field, tables, etc. Container is a component class subclass. Container class keeps track of parts added to a different element. 

  • Panel 

Panel class is a container specific subclass. There is no title bar, menu bar or boundary in the panel. It is a container used to hold parts. 

  • Window class 

Window class produces a window of the highest standard. Window has no boundaries and menu bar. 

  • Frame 

Frame is a Window subclass and can be resized. It is a container containing various parts such as button, title bar, textfield, label, etc. Most AWT apps are developed in Java using the Frame window. Frame class is made up of two distinct builders. 

Frame() throws HeadlessException 
Frame(String title) throws HeadlessException

 

Creating a Frame 

There are two ways to create a Frame. They are, 

  • By Instantiating Frame class 
  • By extending Frame class 

Creating Frame Window by Instantiating Frame class 

import java.awt.*; 
public class Testawt 
{ 
Testawt() 
  { 
    Frame fm=new Frame();    //Creating a frame 
    Label lb = new Label("welcome to java graphics");   //Creating a label 
    fm.add(lb);//adding label to the frame 
    fm.setSize(300, 300);   //setting frame size. 
    fm.setVisible(true);     //set frame visibilty true 
  } 
public static void main(String args[]) 
  { 
    Testawt ta = new Testawt(); 
  } 
} 

Instantiating Frame class

Creating Frame window by extending Frame class

package testawt; 
import java.awt.*; 
import java.awt.event.*; 
public class Testawt extends Frame 
{ 
  public Testawt() 
    { 
        Button btn=new Button("Hello World"); 
        add(btn); //adding a new Button. 
        setSize(400, 500);        //setting size. 
        setTitle("StudyTonight");  //setting title. 
        setLayout(new FlowLayout());//set default layout for frame. 
        setVisible(true);           //set frame visibilty true. 
    } 
     public static void main (String[] args) 
     { 
        Testawt ta = new Testawt();   //creating a frame. 
    } 
} 

extending Frame class


useful links for java : click here
if you want to learn about java then click here

Leave a Comment

Your email address will not be published. Required fields are marked *