0% found this document useful (0 votes)
8 views47 pages

Event Handling in Java

This document explains how to create a menu bar, menus, and menu items in a Java window application using the MenuBar, Menu, and MenuItem classes. It provides examples of handling menu item click events with ActionListener and discusses the Delegation Event Model in Java for managing user interactions. Additionally, it covers various event types, their corresponding listener interfaces, and demonstrates handling TextEvents in text fields and text areas.

Uploaded by

ayushmaurya155
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views47 pages

Event Handling in Java

This document explains how to create a menu bar, menus, and menu items in a Java window application using the MenuBar, Menu, and MenuItem classes. It provides examples of handling menu item click events with ActionListener and discusses the Delegation Event Model in Java for managing user interactions. Additionally, it covers various event types, their corresponding listener interfaces, and demonstrates handling TextEvents in text fields and text areas.

Uploaded by

ayushmaurya155
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Menu, MenuItems and MenuBar class

In this article, we are going to understand how to add a menu bar,


menu and its menu items to the window application.
• A menu bar can be created using MenuBar class.
• A menu bar may contain one or multiple menus, and these
menus are created using Menu class.
• A menu may contain one of multiple menu items and these
menu items are created using MenuItem class.
• Simple constructors of MenuBar, Menu and MenuItem

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");

// Creating a menu bar


menuBar = new MenuBar();

// Creating first menu


menu1 = new Menu("File");
mItem1 = new MenuItem("New");
mItem2 = new MenuItem("Open");
mItem3 = new MenuItem("Save");

// Adding menu items to the Menu


menu1.add(mItem1);
menu1.add(mItem2);
menu1.add(mItem3);

// Creating a second sub-menu


menu2 = new Menu("Save-as");
mItem5 = new MenuItem(".jpeg");
mItem6 = new MenuItem(".png");
mItem7 = new MenuItem(".pdf");

// Adding menu items to the sub-menu


menu2.add(mItem5);
menu2.add(mItem6);
menu2.add(mItem7);

// Adding the sub-menu to the first menu


menu1.add(menu2);

// Adding our menu to the menu bar


menuBar.add(menu1);

// Adding my menu bar to the frame by calling setMenuBar()


method
frame.setMenuBar(menuBar);
frame.setSize(330, 250);
frame.setVisible(true);

// Add window listener to handle closing


frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String[] args) {


new JavaApplication23();
}
}

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());

// Creating a menu bar


menuBar = new MenuBar();

// Creating first menu (File)


menu1 = new Menu("File");
mItem1 = new MenuItem("New");
mItem2 = new MenuItem("Open");
mItem3 = new MenuItem("Save");
mItem4 = new MenuItem("Exit");

// Adding menu items to the File menu


menu1.add(mItem1);
menu1.add(mItem2);
menu1.add(mItem3);
menu1.addSeparator(); // Adds a separator line
menu1.add(mItem4);

// Creating a sub-menu (Save As)


menu2 = new Menu("Save As");
mItem5 = new MenuItem(".jpeg");
mItem6 = new MenuItem(".png");
mItem7 = new MenuItem(".pdf");

// Adding items to the Save As sub-menu


menu2.add(mItem5);
menu2.add(mItem6);
menu2.add(mItem7);

// Adding the sub-menu to the File menu


menu1.add(menu2);

// Adding the menu to the menu bar


menuBar.add(menu1);

// Adding ActionListener to "Open" and "Exit"


mItem2.addActionListener(this);
mItem4.addActionListener(this);

// Adding a label to display selected file


label1 = new Label("", Label.CENTER);
frame.add(label1, BorderLayout.CENTER);

// Setting menu bar and window properties


frame.setMenuBar(menuBar);
frame.setSize(370, 270);
frame.setVisible(true);

// Handle window close event


frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public void actionPerformed(ActionEvent ae) {


if (ae.getActionCommand().equals("Open")) {
// Open a file dialog
fg = new FileDialog(frame, "Open a File", FileDialog.LOAD);
fg.setVisible(true);

String file = fg.getDirectory() + fg.getFile();


if (file != null && !file.equals("nullnull")) {
label1.setText("File to Open: " + file);
}
} else if (ae.getActionCommand().equals("Exit")) {
System.exit(0);
}
}

public static void main(String[] args) {


new MenuEx2();
}
}

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

User interaction with the elements of graphical user interface(GUI) of a


Java program leads to events. These elements could be a button,
checkbox, radio button, menu, list, table, scrollbar, mouse, window etc.
Such elements are also known as source of an event and there is a
specific class corresponding to each source and each event.
Some of the events could be -
• A click on button, checkbox, radio button.
• Selecting a menuitem or list item.
• Clicking or movement of a mouse.
• Entering or editing the data in a textfield.
• Delegation Event Model
Java follows a Delegation Event Model to handle the such events. The
two main components of this model are as follows -
• Source
• Listener
• Source
Interaction with a source generates an event, which is an object of
event class describing the current state of source. A source must
register the listener class that wishes to listen and respond to its event,
by calling a method, which has a general form of -

Public void add EventTypeListener(EventTypeListener el)

where, EventType could be replaced by the name of the type of event.

For example -, A click on a source such as button raises to an event,


which is an object of type ActionEvent class, hence a source button
must call its method addActionListener() to register any class that
wishes to listen and respond to its button event of type ActionEvent.
Listener
The event is delegated to the registered listener classes. In order to
listen and respond to events, such registered listener class must
implement EventTypeListener interface, where, EventType could be
replaced by the name of the type of event.

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.

Event Classes Event Listener Interface


ActionEvent ActionListener
ItemEvent ItemListener
KeyEvent KeyListener
MouseEvent MouseListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
Looking at the two tables, a class wishing to respond to an event of
type KeyEvent, which is generated when a user pressed a key in
textfield or textarea, should -
• Register for listening to KeyEvent by
calling addKeyListener() method on event source class, such
as textfield or textarea, and
• Implement KeyListener interface to respond to event of
type KeyEvent.
ActionEvent and ActionListener

An event of type ActionEvent class is generated when a source such as -


• A button is clicked, or,
• An item in the list is double-clicked, or,
• A menu item is selected in the menu.
• Some methods of ActionEvent class
Method Description
public String Returns the name over the button, item or
getActionCommand() menuitem that was clicked to trigger
the ActionEvent.
public long Returns the time when
getWhen() an ActionEvent was generated.
A class to listen and respond to ActionEvent should take two steps -
• It should implement an interface, ActionListener, by
providing an implementation of its method -

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.

Handling an ActionEvent by implementing ActionListener interface


In the upcoming code, we are going to create a class that will listen
to ActionEvent, by implementing ActionListener interface. In this code,
ActionEvent is generated when a source, i.e. button, is clicked.
import java.awt.*;
import java.awt.event.*;

public class ActionEx1 implements ActionListener {


Frame jf;
Button button1, button2;
Label label;

ActionEx1() {
jf = new Frame("Button click events");
button1 = new Button("Button1");
button2 = new Button("Button2");
label = new Label("", Label.CENTER); // Initialize with empty text

// Set layout and add components


jf.setLayout(new FlowLayout(FlowLayout.CENTER, 60, 10));
jf.add(button1);
jf.add(button2);
jf.add(label);

// Register action listeners


button1.addActionListener(this);
button2.addActionListener(this);

// Add window listener to handle closing


jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});

jf.setSize(250, 150);
jf.setVisible(true);
}

public void actionPerformed(ActionEvent ae) {


if (ae.getActionCommand().equals("Button1")) {
label.setText("You've clicked Button1");
}
if (ae.getActionCommand().equals("Button2")) {
label.setText("You've clicked Button2");
}
}

public static void main(String[] args) {


new ActionEx1();
}
}
When you run the code, you are presented a window with two buttons
shown in the Figure1 below -:

Figure 1

When you click on any of the buttons, you will be displayed an


appropriate message, for example, when you click on Button1 button,
you get a message "You've clicked on Button1", as shown in figure
below.
Figure 2
TextEvent and TextListener

An event of type TextEvent is generated when a value in textfield or


textarea is entered or edited. A class that wants to listen and respond to
an event of type TextEvent, must implement the TextListener interface.

Method of TextEvent class

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.

Handling an TextEvent in a TextField by implementing TextListener


interface
In this upcoming code, we are going to listen to TextEvent in a textfield,
by implementing the TextListener interface.

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

An event of type KeyEvent class is generated when a source such as,


a key on the keyboard is pressed in a textfield or in a textarea.
Some methods of KeyEvent class

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.

Handling an KeyEvent by implementing KeyListener interface


In the upcoming code, we are going to create a class that will listen to
an event of type KeyEvent, by implementing the KeyListener interface.
In this code, the KeyEvent is generated when a key is pressed and
released within a textfield.
importjava.awt.*;
importjava.awt.event.*;
publicclassKeyEx1implementsKeyListener{
Label label1, label2;
TextField field1;
Frame jf;
String str;
KeyEx1()
{
jf = newFrame("Handling KeyEvent");
label1= newLabel("Press any key on keyboad, to see the events it
generates -", Label.CENTER);
label2= newLabel();
field1 = newTextField(20); //calling
TextField(String)jf.setLayout(newFlowLayout());
jf.add(label1);
jf.add(field1);
jf.add(label2);
field1.addKeyListener(this); //As soon as button is clicked, data from
all the textfields is readjf.setSize(360,200);
jf.setVisible(true);
}
publicvoidkeyPressed(KeyEvent ke){
str= "KeyCode : "+ ke.getKeyCode() + ", -Key Pressed- ";
label2.setText(str);
jf.setVisible(true);
}
publicvoidkeyReleased(KeyEvent ke){
str+=" -Key Released- ";
label2.setText(str);
jf.setVisible(true);
str="";
}
publicvoidkeyTyped(KeyEvent ke){
str+=" -Key Typed- ";
label2.setText(str);
jf.setVisible(true);
}
publicstaticvoidmain(String... ar){
newKeyEx1();
}
}
When you run the code, you are presented a window shown in the
window below -:

Figure 1

When you press a 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 a -
Figure 2

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

>Calculator Program in java AWT


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

public class Main implements ActionListener {


Frame frame;
Button addBtn, subBtn, mulBtn, divBtn;
TextField num1Field, num2Field;
Label operationLabel, resultLabel;

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");

num1Field = new TextField();


num2Field = new TextField();

operationLabel = new Label("Select an operation", Label.CENTER);


resultLabel = new Label("Result will appear here", Label.CENTER);

// 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);

// Set bounds (x, y, width, height)


num1Field.setBounds(150, 50, 200, 30);
num2Field.setBounds(150, 100, 200, 30);

addBtn.setBounds(50, 150, 80, 40);


subBtn.setBounds(150, 150, 80, 40);
mulBtn.setBounds(250, 150, 80, 40);
divBtn.setBounds(350, 150, 80, 40);

operationLabel.setBounds(50, 200, 400, 30);


resultLabel.setBounds(50, 250, 400, 50);

// Add components to frame


frame.add(new Label("First Number:")).setBounds(50, 50, 100, 30);
frame.add(num1Field);
frame.add(new Label("Second Number:")).setBounds(50, 100, 100,
30);
frame.add(num2Field);
frame.add(addBtn);
frame.add(subBtn);
frame.add(mulBtn);
frame.add(divBtn);

frame.add(operationLabel);
frame.add(resultLabel);

// Add action listeners


addBtn.addActionListener(this);
subBtn.addActionListener(this);
mulBtn.addActionListener(this);
divBtn.addActionListener(this);

// Window listener for closing


frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

frame.setVisible(true);
}

public void actionPerformed(ActionEvent e) {


try {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
double result = 0;
String operation = "";

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
}

operationLabel.setText(operation + " performed");


resultLabel.setText("Result: " + result);

} catch (NumberFormatException ex) {


resultLabel.setText("Error: Please enter valid numbers!");
operationLabel.setText("Invalid input");
frame.setBackground(Color.lightGray);
}
}

public static void main(String[] args) {


new Main();
}
}

MouseEvent and MouseMotionListener

In order to handle mouse motion events in an appliction i.e. events


which are generated when a mouse is moved, we need to work
with MouseEvent class. An event of type MouseEvent class is generated
in mouse motion situations like -
• When a mouse is moved.
• When a mouse button is being pressed and dragged.
In order to create a class that handles mouse motion events, we need
to understand some important methods of MouseEvent class in the
table below.
Some methods of MouseEvent class

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.

A class to listen and respond to event type MouseEvent, must perform


two steps:
• A class that wants to handle and respond to mouse motion events
of type MouseEvent should implement an interface
i.e. MouseMotionListener and also provide implementation of its
methods shown in the table below -

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.

Handling an MouseEvent by implementing MouseListener interface


In the upcoming example, we are going to handle mouse motion events
such as -
• When a mouse is moved within the Frame's window area.
• When a mouse button is pressed and dragged within the
Frame's window.

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

An event of type ItemEvent is generated when a source such as a


checkbox is clicked to check/uncheck it or when a list item is clicked. A
class to listen and respond to an event of type, ItemEvent, must
implement an interface, ItemListener.
Some methods of ItemEvent class

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.

Handling an ItemEvent by implementing ItemListener interface


In the upcoming code, we are going to create a class that will listen to
an event of type, ItemEvent, by implementing
the ItemListener interface. In this code, ItemEvent is generated when a
source, i.e. checkbox, is clicked to check/uncheck it.

//Java - Example of ItemEvent and ItemListenerimportjava.awt.*;


importjava.awt.event.*;
publicclassItemEx1implementsItemListener{
Frame jf;
Checkbox chk1, chk2;
Label label1;
ItemEx1()
{
jf= newFrame("Checkbox");
chk1 = newCheckbox("Happy");
chk2 = newCheckbox("Sad");
label1 = newLabel();
jf.add(chk1);
jf.add(chk2);
chk1.addItemListener(this);
chk2.addItemListener(this);
jf.setLayout(newFlowLayout());
jf.setSize(220,150);
jf.setVisible(true);
}
publicvoiditemStateChanged(ItemEvent ie){
Checkbox ch =(Checkbox)ie.getItemSelectable();
if(ch.getState()==true)
{
label1.setText(ch.getLabel()+ " is checked");
jf.add(label1);
jf.setVisible(true);
}
else{
label1.setText(ch.getLabel()+ " is unchecked");
jf.add(label1);
jf.setVisible(true);
}
}
publicstaticvoidmain(String... ar){
newItemEx1();
}
}
When you run the code, you are presented a window shown in the
Figure2 below -:

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

An event of type WindowEvent is generated in such situations -


• When a window is activated for the first time.
• When a window is minimized.
• When a window is brought up back from minimized state.
• When the close button (x) of window is clicked to close it.
• Some methods of WindowEvent class

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.

Handling an WindowEvent by implementing WindowListener interface


In the upcoming code, we are going to create a class that will listen
to WindowEvent, by implementing WindowListener interface. In this
code, WindowEvent is generated when a key is pressed and released
within a textfield.

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 bring up the minimized window, the window is reactivated.


Figure 3

Hence, a new message is displayed on the command prompt, due to the


execution of the method:
• windowActivated()
Window Activated

When you click on the (x) button of this window to close it, the window
is deactivated and closed.

Figure 4

Hence, three new messages are displayed on the command prompt,


due to the execution of methods in sequence:
• windowClosing()
• windowDeactivated()
• windowClosed()
Window Closing
Window Deactivated
Window Closed

AdjustmentEvent and AdjustmentListener

An event of type AdjustmentEvent is generated when a scrollbar is


dragged around.
Some methods of AdjustmentEvent class

Methods Description
public int getValue() Gets the Scrollbar's current position value.
public int Returns the type of adjustment that
getAdjustmentType() caused AdjustmentEvent.

A class to listen and respond to AdjustmentEvent, must perform the


two steps:

•It should implement an interface, AdjustmentListener by


implementing its methods -
Methods Description
public void This method is
adjustmentValueChanged(AdjustmentEvent called when the
e) scrollbar has been
dragged around.
• An AdjustmentEvent source which is a scrollbar, must call its
method -
Methods Description
public void where object is an object of
addAdjustmentListener(Adjustme the class that has
ntListener object) implemented AgjustmentList
ener interface. Doing this,
registers the class to listen
and respond to mouse move
and drag AdjustmentEvent.

Handling an AdjustmentEvent by implementing AdjustmentListener


interface
In this upcoming code, we are going to listen to the movement of
scrollbar which triggers AdjustmentEvent, by implementing
the AdjustmentListener interface.

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.

You might also like