Event Handling in Java
Event Handling in Java
Constructor Description
public Creates a menu bar to
MenuBar() which one or many menus
are added.
public Creates a menu with a
Menu(String title.
title)
public Creates a menu item with
MenuItem(String a title.
title)
Creating a menu, menu items and a submenu.
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication23;
import java.awt.*;
import java.awt.event.*;
public class JavaApplication23 {
Frame frame;
MenuBar menuBar;
Menu menu1, menu2;
MenuItem mItem1, mItem2, mItem3, mItem4, mItem5, mItem6,
mItem7;
JavaApplication23() {
frame = new Frame("MenuBar, Menu and MenuItems");
When you run the code, you are presented a window that shows a
menu named File
Figure 1
When you click on this menu named File, you are presented its menu
items such as New, Open, Save and its sub-menu Save-as and its menu
items such as .jpeg, .pdf, .png.
Figure 2
Handling click events on menu items using ActionListener.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class MenuEx2 implements ActionListener {
Frame frame;
MenuBar menuBar;
Menu menu1, menu2;
MenuItem mItem1, mItem2, mItem3, mItem4, mItem5, mItem6,
mItem7;
FileDialog fg;
Label label1;
MenuEx2() {
frame = new Frame("File Dialog Example");
frame.setLayout(new BorderLayout());
When you run the code, you are presented a window that shows the
same menu as we have seen on executing the previous program.
Figure 3
When you click on the menu item named Open, a file chooser dialog
window opens us, using which you can choose any file in your computer
that you wish to open.
Figure 4
When you select this file, you are presented its path.
Figure 5
In the another response to menu items being clicked, when you click
the Exit menu item of our program, the program exits and gets closed.
Events in Java
For example - A class wishing to listen and respond to the a button click
event(which is an object of type ActionEvent), must
implement ActionListener interface.
Interaction with elements of GUI raises events, which are nothing but
objects of classes. EventObject is the superclass of all the events. Let's
see a table containing some different kinds of event classes and
the description of their events.
Event Classes Description
ActionEvent ActionEvent is generated when a source such
as a button is clicked, an item in the list is
double-clicked or when a menu item is
selected.
ItemEvent ItemEvent is generated when a source such as
a checkbox is clicked to check/uncheck it or
when a list item is clicked.
KeyEvent KeyEvent is generated when a source such as a
key on the keyboard pressed in a textfield or a
textarea.
MouseEvent MouseEvent is generated when a source such
a mouse is moved, dragged, enters/exits a
specific window or when it's button is
clicked/released.
TextEvent TextEvent is generated when a data in textarea
or textfield is changed.
AdjustmentEvent AdjustmentEvent is generated when a
scrollbar is dragged around.
WindowEvent WindowEvent is generated when a source
such as a window is activated, minimized,
brought up, deactivated and closed.
Let's see a table of some important event classes and
their corresponding interfaces that should be implemented by classes in
order to listen and respond to the events.
Method Description
public void Invoked when an Action Event is
actionPerformed(ActionEvent generated.
ae)
• An ActionEvent source which could be a button, menuitem
or a list item, must call this method -
Method Description
public void where object is an object of
addActionListener(ActionListene the class that has
r object) implemented ActionListener i
nterface and wanted to
register itself to listen and
respond
to ActionEvent generated by a
click on this specific source.
ActionEx1() {
jf = new Frame("Button click events");
button1 = new Button("Button1");
button2 = new Button("Button2");
label = new Label("", Label.CENTER); // Initialize with empty text
jf.setSize(250, 150);
jf.setVisible(true);
}
Figure 1
Methods Description
public String Returns the String describing the TextEvent.
paramString()
A class to listen and respond to a TextEvent, must perform the two
steps:
• It should implement an interface, TextListener and provide
implementation of its methods -
Methods Description
public void This method is called when a value
textValueChanged(TextEvent in textfield or textarea is entered
e) or edited.
• The source of the event type TextEvent, must call its method
-
Methods Description
public void Where, object is an object of the class that
addTextListener( has implemented
TextListener object ) the TextListener interface. Doing this,
registers the class to listen and respond to
an event of type TextEvent, when a textfield
or textarea is entered or edited.
importjava.awt.*;
importjava.awt.event.*;
publicclassTextEventEx1implementsTextListener{
Label label1, label2;
TextField field1;
Frame jf;
String str;
TextEventEx1()
{
jf = newFrame("Handling TextEvent");
label1= newLabel("Type in the textfield, to see the textevents it
generates -", Label.CENTER);
label2= newLabel();
field1 = newTextField(25);
jf.setLayout(newFlowLayout());
jf.add(label1);
jf.add(field1);
jf.add(label2);
//Registering the class TextEventEx1 to catch and respond to mouse
text events field1.addTextListener(this);
jf.setSize(340,200);
jf.setVisible(true);
}
publicvoidtextValueChanged(TextEvent te){
label2.setText(te.paramString());
jf.setVisible(true);
}
publicstaticvoidmain(String... ar){
newTextEventEx1();
}
}
When you run the code, you are presented a window that shows an
empty textfield.
Figure 1
When this textfield is active and if you type in any character or digit, you
are notified about the change in textfield value by a
constant TEXT_VALUE_CHANGED of TextEvent class.
Figure 2
Handling an TextEvent in a TextArea by implementing TextListener
interface
In this upcoming code, we are going to listen to TextEvent in a textarea,
by implementing the TextListener interface.
importjava.awt.*;
importjava.awt.event.*;
publicclassTextEventEx2implementsTextListener{
Label label1, label2;
TextArea area1;
Frame jf;
String str;
TextEventEx2()
{
jf = newFrame("Handling TextEvent");
label1= newLabel("Type in the TextArea, to see the TextEvent -",
Label.CENTER);
label2= newLabel();
area1 = newTextArea(5,20); //calling
TextField(String)jf.setLayout(newFlowLayout());
jf.add(label1);
jf.add(area1);
jf.add(label2);
//Registering the class TextEventEx2 to catch and respond to mouse
text events area1.addTextListener(this);
jf.setSize(300,200);
jf.setVisible(true);
}
publicvoidtextValueChanged(TextEvent te){
label2.setText(te.paramString());
jf.setVisible(true);
}
publicstaticvoidmain(String... ar){
newTextEventEx2();
}
}
When you run the code, you are presented a window that shows an
empty textarea.
Figure 3
When this textarea is active and if you type in any character or digit,
you are notified about the change in textarea's value by a
constant TEXT_VALUE_CHANGED of TextEvent class.
Figure 4
KeyEvent and KeyListener
Method Description
public char Returns the character associated with the key
getKeyChar() pressed on the keyboard, which triggered
the KeyEvent.
Returns an int key code associated with the key
public int pressed on the keyboard.
getKeyCode()
Returns true if key pressed was an "action" key, i.e.
keys that don't generate a character, such as Cut,
public Copy, Paste, Page Up, Caps Lock, the arrow and
boolean function keys.
isActionKey()
A class to listen and respond to a KeyEvent, must perform the next two
steps -
• It should implement an interface, KeyListener, by providing
an implementation of its three methods -
Method Description
public void This method is called when a key is
keyPressed(KeyEvent pressed on the keyboard.
e)
This method is called when a key is
public void released on the keyboard.
keyReleased(KeyEvent
ke)
This method is called when pressing a key
public void on they keyboard has resulted in a
keyTyped(KeyEvent character.
ke)
• A KeyEvent source which could be a textfield or a textarea,
must call its method -
Method Description
public void where, object is an object of
addKeyListener(KeyListener obj the class that has
ect) implemented KeyListener interf
ace and wanted to register
itself to listen and respond
to ActionEvent generated when
a key is pressed in this source.
Figure 1
When you press SHIFT key on the keyboard, it triggers a KeyEvent, but
this time two methods defined in KeyEventEx1 are called in sequence -
• keyPressed()
• keyReleased()
Method keyTyped() is not called because SHIFT key doesn't generate or
remove any character. You are presented a window showing the co de
of key SHIFT -
Figure 3
When you press Backspace key on the keyboard, it triggers a KeyEvent,
three methods defined in KeyEventEx1 are called in sequence -
• keyPressed()
• keyTyped()
• keyReleased()
And you are presented a window showing the code of key Backspace-
Figure 4
public Main() {
// Initialize frame
frame = new Frame("AWT Calculator");
frame.setLayout(null);
frame.setSize(500, 400);
frame.setBackground(Color.lightGray);
// Create components
addBtn = new Button("Add");
subBtn = new Button("Subtract");
mulBtn = new Button("Multiply");
divBtn = new Button("Divide");
// Set fonts
Font btnFont = new Font("Arial", Font.BOLD, 14);
Font resultFont = new Font("Arial", Font.BOLD, 18);
addBtn.setFont(btnFont);
subBtn.setFont(btnFont);
mulBtn.setFont(btnFont);
divBtn.setFont(btnFont);
resultLabel.setFont(resultFont);
frame.add(operationLabel);
frame.add(resultLabel);
frame.setVisible(true);
}
if (e.getSource() == addBtn) {
result = num1 + num2;
operation = "Addition";
frame.setBackground(new Color(200, 255, 200)); // Light green
}
else if (e.getSource() == subBtn) {
result = num1 - num2;
operation = "Subtraction";
frame.setBackground(new Color(255, 200, 200)); // Light red
}
else if (e.getSource() == mulBtn) {
result = num1 * num2;
operation = "Multiplication";
frame.setBackground(new Color(200, 200, 255)); // Light blue
}
else if (e.getSource() == divBtn) {
if (num2 == 0) {
resultLabel.setText("Error: Cannot divide by zero!");
operationLabel.setText("Division attempted");
frame.setBackground(new Color(255, 255, 200)); // Light
yellow
return;
}
result = num1 / num2;
operation = "Division";
frame.setBackground(new Color(255, 200, 255)); // Light
purple
}
Method Description
public Point Returns the absolute x, y position of
getLocationOnScreen() the MouseEvent.
public int getX() Returns the x-coordinate of
the MouseEvent.
public int getY() Returns the y-coordinate of
the MouseEvent.
Method Description
public void This method is called when a
mouseMoved(MouseEvent mouse cursor moves in a window
me) listening for mouse motion event
of type MouseEvent.
public void This method is called when a
mouseDragged(MouseEvent mouse cursor is being dragged in a
me) window listening for mouse motion
event of type MouseEvent.
• A MouseEvent source is a window in which such event is
generated, must call its method -
Method Description
public void where object is an object of
addMouseMotionListener(Mouse the class that has
MotionListener object) implemented MouseMotion
Listener interface. Doing
this, registers the class to
listen and respond to mouse
move and drag MouseEvent.
mportjava.awt.*;
importjava.awt.event.*;
importjava.awt.Point;
publicclassMouseEx3extendsWindowAdapterimplementsMouseMotion
Listener{
Label label1, label2;
Frame frame;
String str;
Point p;
MouseEx3()
{
frame = newFrame("Window");
label1= newLabel("Tracking mouse cursor in the Frame window",
Label.CENTER);
label2= newLabel();
frame.setLayout(newFlowLayout());
frame.add(label1);
frame.add(label2);
//Registering class MouseEx1 to catch and respond to mouse motion
motion events frame.addMouseMotionListener(this);
//Registering class MouseEx3 to catch and respond to window event i.e.
window closing eventframe.addWindowListener(this);
frame.setSize(280,200);
frame.setVisible(true);
}
//Method of WindowAdapter class to catch and respond to window
closing eventpublicvoidwindowClosing(WindowEvent we){
System.exit(0);
}
//Method of MouseMotionListener
interfacepublicvoidmouseDragged(MouseEvent me){
String s = me.getX() + ","+ me.getY();
label2.setText("Mouse dragged "+ s);
frame.setVisible(true);
}
//Method of MouseMotionListener
interfacepublicvoidmouseMoved(MouseEvent me){
String s = me.getX() + ","+ me.getY();
label2.setText("Mouse moved "+ s);
frame.setVisible(true);
}
publicstaticvoidmain(String... ar){
newMouseEx3();
}
}
When you run the code, you are presented a window shown in the
window below -:
Figure 1
When you move your mouse cursor in the Frame's window area, it
generates an event i.e. MouseEvent. Method mouseMoved() is
executed to handle mouse movement event and as you move your
mouse cursor, you are notified about the current x and y coordinates of
your mouse cursor in the window :
• mouseMoved()
Figure 2
When you drag your mouse cursor within the Frame's window area, it
generates a MouseEvent, the method mouseDragged() is executed to
handle mouse drag event and you are notified about current x and y
coordinates of your mouse cursor in the window, where the mouse is
dragged :
Figure 3
ItemEvent and ItemListener
Method Description
public Object Returns the item which was clicked and
getItem() triggered the ItemEvent.
Returns the item which was clicked.
public
ItemSelectable
getItemSelectable()
Returns the current state of item which was
public int clicked.
getStateChange()
A class to listen and respond to ItemEvent must perform the next two
steps -
• It should implement an interface, ItemListener, by providing
an implementation of its method:
Method Description
public void Invoked when an item has been
itemStateChanged(ItemEvent selected or deselected by the
e) user.
• A ItemEvent event source which could be a checkbox or a
list, must call its method -
Method Description
public void where object is an object of the
addItemListener(ItemListener o class that has
bject) implemented ItemListener inte
rface. Doing this, registers the
class to listen and respond
to ItemEvent, generated by a
click on this specific source.
Figure 1
When you check a checkbox an event ItemEvent is fired and you are
presented a message to display which checkbox is last
checked/unchecked. For example, when you check the checkbox with
label- happy, you are notified like -
Figure 2
When you uncheck this checkbox, an event ItemEvent is fired you are
notified with a message that you've unchecked the checkbox(including
its name).
Figure 3
WindowEvent and WindowListener
Method Description
public Returns the window which triggered
Window the WindowEvent.
getWindow()
public int Returns the new state of the window.
getNewState()
A class to listen & respond to a WindowEvent must perform the next
two steps:
• It should implement WindowListener interface, by
implementing its all next seven methods -
Method Description
public void This method is called when a
windowOpened(WindowEvent e) window is opened for the
first time.
public void This method is called when a
windowActivated(WindowEvent window shows up on screen.
e)
public void This method is called is no
windowDeactivated(WindowEvent longer the window in use or
e) active.
public void This method is called when a
windowIconified(WindowEvent e) window is changed from a
normal to a minimized state.
public void This method is called when a
windowDeiconified(WindowEvent window is brought up on the
e) screen from a minimized
state.
public void This method is called a user
windowClosing(WindowEvent ke) clicks on the (x) icon to close
the window.
public void This method is called when a
windowClosed(WindowEvent e) window has been closed.
• A WindowEvent event source is a window in which such
event is generated, must call its method -
Method Description
public void where object is an object of
addWindowListener(ItemListen the class that has
er object) implemented Windowistener i
nterface. Doing this, registers
the class to listen and respond
to WindowEvent.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
publicclassWindowEx1implementsWindowListener{
Label label1;
Frame frame;
WindowEx1()
{
frame = newFrame("Handling KeyEvent");
label1= newLabel("-See window events -", Label.CENTER);
frame.setLayout(newFlowLayout());
frame.add(label1);
//Registering class WindowEx1 to catch and respond to window
events frame.addWindowListener(this);
frame.setSize(340,200);
frame.setVisible(true);
}
publicvoidwindowActivated(WindowEvent we)
{
System.out.println("Window Activated");
}
publicvoidwindowClosed(WindowEvent we)
{
System.out.println("Window Closed");
}
publicvoidwindowClosing(WindowEvent we)
{
frame.dispose();
System.out.println("Window Closing");
}
publicvoidwindowDeactivated(WindowEvent we)
{
System.out.println("Window Deactivated");
}
publicvoidwindowDeiconified(WindowEvent we)
{
System.out.println("Window Deiconified");
}
publicvoidwindowIconified(WindowEvent we)
{
System.out.println("Window Iconified/minimized");
}
publicvoidwindowOpened(WindowEvent e)
{
System.out.println("Window Opened for the first time");
}
publicstaticvoidmain(String... ar)
{
newWindowEx1();
}
}
When you run the code, you are presented a window shown in the
window below -:
Figure 1
At the command prompt you are displayed two messages, due to the
execution of methods in sequence:
• windowActivated()
• windowOpened()
Window Activated
Window Opened forthe first time
When you click on the minimize button of this window to minimize it,
the window is deactivated and deiconified.
Figure 2
Hence, two new messages are displayed on the command prompt, due
to the execution of methods in sequence:
• windowDeiconified()
• windowDeactivated()
Window Iconified/minimized
Window Deactivated
When you click on the (x) button of this window to close it, the window
is deactivated and closed.
Figure 4
Methods Description
public int getValue() Gets the Scrollbar's current position value.
public int Returns the type of adjustment that
getAdjustmentType() caused AdjustmentEvent.
importjava.awt.*;
importjava.awt.event.*;
publicclassScrollEx2implementsAdjustmentListener{
Frame jf;
Panel jp, jp2;
Label frameLabel1;
ScrollEx2()
{
jf = newJFrame("Scrollbar");
//Creating the first JPanel and adding two JLabels to itjp =
newPanel();
//Creating a Label Label panelLabel1 = newLabel("Handling a Scrollbar
drag event", Label.CENTER);
jp = newPanel(newBorderLayout());
//Adding the Label to NORTH of the
Paneljp.add(panelLabel1,BorderLayout.NORTH);
//Creating the horizontal ScrollbarScrollbar scrollBHorizontal =
newScrollbar(Scrollbar.HORIZONTAL, 10, 40, 0, 100);
//Creating the vertical ScrollbarScrollbar scrollBVertical =
newScrollbar(Scrollbar.VERTICAL, 10, 60, 0, 100);
//Adding the horizontal Scrollbar to SOUTH of
Paneljp.add(scrollBHorizontal,BorderLayout.SOUTH);
//Adding the vetical Scrollbar to EAST of JPaneljp.add(scrollBVertical,
BorderLayout.EAST);
//Getting the current position value of horizontal scrollbarInteger i =
scrollBHorizontal.getValue();
//Creating a JLabel and setting its value to the current position value of
horizontal scrollbar.frameLabel1 = newLabel(i.toString());
//Adding this JLabel to SOUTH of the JFramejf.add(frameLabel1,
BorderLayout.SOUTH);
//Adding the first JPanel to the CENTER of
JFramejf.add(jp,BorderLayout.CENTER);
//Registering class ScrollEx2 to catch and respond to scrollbar
adjustment events scrollBHorizontal.addAdjustmentListener(this);
scrollBVertical.addAdjustmentListener(this);
jf.setSize(350,270);
jf.setVisible(true);
}
publicvoidadjustmentValueChanged(AdjustmentEvent e){
Integer i =e.getValue();
frameLabel1.setText(i.toString());
}
publicstaticvoidmain(String... ar){
newScrollEx2();
}
}
When you run the code, you are presented a window that shows an
image, with two Scrollbar, i.e. a horizontal and a vertical scrollbar
beneath the horizontal Scrollbar, you are shown the number that shows
the current position value of Scrollbar.
Figure 1
When you drag any of the scrollbar(horizontal or vertical), you may see
the change in the current position value of the scrollbar which you are
dragging.