Lab Manual 07
Lab Manual 07
Lab Manual No 07
Dated:
Semester:
Spring 2024
91 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
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 .
Event Handling 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.
e) 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.
f) Listener − It is also known as event handler. The listener is responsible for generating a response to an
event. From the point of view of Java implementation, the listener is also an object. The listener waits till it
receives an event. Once the event is received, the listener 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 listener needs to be registered with the source object so that the listener can receive the event
notification. This is an efficient way of handling the event because the event notifications are sent only to those
listeners who want to receive them.
Step 1 − The user clicks 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 listener class.
92 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
f) In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces
forecast some public abstract callback methods, which must be implemented by the listener class.
g) If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a
source object.
Callback Methods
These are the methods that are provided by API provider and are defined by the application programmer and invoked
by the application 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 listener interfaces.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
93 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For example:
c) Button
o public void addActionListener(ActionListener a){}
o MenuItem
4 TextArea
7 Checkbox
9 Choice
94 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
We can put the event handling code into one of the following places:
17 Within class
18 Anonymous class
95 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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));
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");
96 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
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();
97 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
b.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
tf.setText("Hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
98 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Within Class
Anonymous inner classes
public static void main(String[] args) { public static void main(String[] args) {
... ...
ActionListener listener = new MyListener(); butt.addActionListener(new ActionListener()
{
butt.addActionListener(listener); public void actionPerformed(ActionEvent e)
... {
} JOptionPane.showMessageDialog(null, "You
clicked me!");
class MyListener implements ActionListener { }
public void actionPerformed(ActionEvent e) { });
}
JOptionPane.showMessageDialog(null, "You
clicked me!");
}
}
99 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
MouseEvent01(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
new MouseEvent01();
100 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.awt.*;
import java.awt.event.*;
public class MouseEvent01 extends Frame implements
MouseListener{ MouseEvent01(){
addMouseListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements MouseMoti
onListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
101 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
The Java WindowListener is notified whenever you change the state of window. It is notified against WindowEvent.
The WindowListener interface is found in java.awt.event package. It has three methods.
102 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Example
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class WindowExample extends Frame implements
WindowListener{ WindowExample(){
addWindowListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);
}
103 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Adapters are abstract classes for receiving various events. The methods in these classes are empty. These classes
exist as convenience for creating listener objects.
SWING Adapters
Following is the list of commonly used adapters while listening GUI events in SWING.
FocusAdapter
1
KeyAdapter
2 An abstract adapter class for receiving key events.
MouseAdapter
3 An abstract adapter class for receiving mouse events.
MouseMotionAdapter
4 An abstract adapter class for receiving mouse motion events.
WindowAdapter
// An abstract adapter class for receiving window events.
104 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Example
In the following code shows how to use FocusAdapter.focusGained(FocusEvent e) method.
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
}
}
105 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.awt.*;
import java.awt.event.*;
public class AdapterExample{
Frame f;
AdapterExample(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){ public
void windowClosing(WindowEvent e) {
f.dispose();
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
106 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.awt.*;
import java.awt.event.*;
public class MouseMotionAdapterExample extends MouseMotionAdapter{
Frame f;
MouseMotionAdapterExample(){
f=new Frame("Mouse Motion Adapter");
f.addMouseMotionListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
// for Closing Window
f.addWindowListener(new WindowAdapter(){ public
void windowClosing(WindowEvent e) {
f.dispose();
}
});
// For Closing
}
public void mouseDragged(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.ORANGE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
107 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter{
Label l;
TextArea area;
Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
We can close the AWT Window or Frame by calling dispose() or System.exit() inside windowClosing() method. The
windowClosing() method is found in WindowListener interface and WindowAdapter class.
The WindowAdapter class implements WindowListener interfaces. It provides the default implementation of all the 7
methods of WindowListener interface. To override the windowClosing() method, you can either use WindowAdapter
class or WindowListener interface.
If you implement the WindowListener interface, you will be forced to override all the 7 methods of WindowListener
interface. So it is better to use WindowAdapter class .
108 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
// By anonymous class
// By inheriting WindowAdapter class
// By implementing WindowListener interface
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; import
java.awt.event.WindowListener; public
class WindowExample01 extends Frame{
WindowExample01(){
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
dispose();
}
});
setSize(400,400);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new WindowExample01();
}
}
109 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
import java.awt.*;
import java.awt.event.*;
public class WindowExample01 extends
WindowAdapter{ Frame f;
WindowExample01(){
f=new Frame();
f.addWindowListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
f.dispose();
}
public static void main(String[] args) {
new AdapterExample();
}
}
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class WindowExample01 extends Frame implements
WindowListener{ WindowExample01(){
addWindowListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);
}
110 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Lab Task
Question No 1
Given in the program below is ActionListener that checks for an action performed on button.
Every-time clicking button will change its background color randomly. Output produced by
clicking button several times is shown below:
Question No 02
// Create GUI for login page using Grid and Border Layout. Class specifications are as follows:
111 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Question No 03
// Create a GUI for Color Selector class. This will set panel color according to user’s selection. A
combo-box will be used to display list of available colors. And a label will also be used to show
selected color.
112 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Question No 04
// Create GUI for simple calculator as shown below and add following functionality using event
handling.
Backspace
It will remove the last entered digit.
CE
It will clear the current text box value.
C
It will clear the values and set the text field.
+
It will add the numbers
-
It will subtract the numbers
*
It will multiply the numbers
/
It will divide the numbers
%
It returns the reminder of the numbers
Sqrt
It returns the square root of the number.
1/x
It will take the reciprocal of the number.
+/-
It will change the sign of the number.
.
It will add the point in the number.
Note: A number can have only a single point.
=
It will return the answer of the calculation.
113 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Question No 05
Create a GUI to detect locations where mouse clicked on frame. For this you need to implement
MouseListener interface to positions where mouse clicked. A menu-bar consisting of three
menus will display menu as follows:
•
Location: will display x and y locations where mouse clicked
•
X Location: will display x locations where mouse clicked
•
Y Location: will display y location where mouse clicked
114 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Question No 06
Making use of adapter class for WindowListener i.e. WindowAdapter open a new window before
closing the previous one. A dialog-box should ask user whether to open a new window or not? If
user enters “yes” then open a new window else do nothing.
115 | P a g e
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION
ENGINEERING COMPUTER ENGINEERING DEPARTMENT
Question No 07
Using All Skills that you Learn Build a CV Generator that Will Take Information from User and Print it on next Window form .
116 | P a g e