Unit 5
Unit 5
EVENT HANDALING:
An event listener in Java is designed to process some kind of event — it "listens" for an event,
such as a user's mouse click or a key press, and then it responds accordingly. An event listener
must be connected to an event object that defines the event.
For example, graphical components like a JButton or JTextField are known as event sources.
This means that they can generate events (called event objects), such as providing a JButton for a
user to click, or a JTextField in which a user can enter text. The event listener's job is to catch
those events and do something with them.
Note that event listeners are flexible in that a single listener can be registered to "listen" to
multiple types of events. This means that, for a similar set of components that perform the same
type of action, one event listener can handle all the events.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListene
Steps to perform Event Handling
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
The Delegation Event model is defined to handle events in GUI programming languages.
The GUI stands for Graphical User Interface, where a user graphically/visually interacts with the
system.
The GUI programming is inherently event-driven; whenever a user initiates an activity such as a
mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a code to
respond to functionality to the user. This is known as event handling.
In this section, we will discuss event processing and how to implement the delegation event
model in Java. We will also discuss the different components of an Event Model.
Java support event processing since Java 1.0. It provides support for AWT ( Abstract Window
Toolkit), which is an API used to develop the Desktop application. In Java 1.0, the AWT was
based on inheritance. To catch and process GUI events for a program, it should hold subclass
GUI components and override action() or handleEvent() methods. The below image
demonstrates the event processing.
But, the modern approach for event processing is based on the Delegation Model. It defines a
standard and compatible mechanism to generate and process events. In this model, a source
generates an event and forwards it to one or more listeners. The listener waits until it receives an
event. Once it receives the event, it is processed by the listener and returns it. The UI elements
are able to delegate the processing of an event to a separate function.
The key advantage of the Delegation Event Model is that the application logic is completely
separated from the interface logic.
In the older model, an event was propagated up the containment until a component was handled.
This needed components to receive events that were not processed, and it took lots of time. The
Delegation Event model overcame this issue.
o Events
o Events Sources
o Events Listeners
Events
The Events are the objects that define state change in a source. An event can be generated as a
reaction of a user while interacting with GUI elements. Some of the event generation activities
are moving the mouse pointer, clicking on a button, pressing the keyboard key, selecting an item
from the list, and so on. We can also consider many other user operations as events.
The Events may also occur that may be not related to user interaction, such as a timer expires,
counter exceeded, system failures, or a task is completed, etc. We can define events for any of
the applied actions.
Event Sources
A source is an object that causes and generates an event. It generates an event when the internal
state of the object is changed. The sources are allowed to generate several different types of
events.
A source must register a listener to receive notifications for a specific event. Each event contains
its registration method. Below is an example:
From the above syntax, the Type is the name of the event, and e1 is a reference to the event
listener. For example, for a keyboard event listener, the method will be called
as addKeyListener(). For the mouse event listener, the method will be called
as addMouseMotionListener(). When an event is triggered using the respected source, all the
events will be notified to registered listeners and receive the event object. This process is known
as event multicasting. In few cases, the event notification will only be sent to listeners that
register to receive them.
From the above syntax, the Type is the name of the event, and e2 is the event listener's reference.
When the specified event occurs, it will be notified to the registered listener. This process is
known as unicasting events.
A source should contain a method that unregisters a specific type of event from the listener if not
needed. Below is an example of the method that will remove the event from the listener.
1. public void removeTypeListener(TypeListener e2?)
From the above syntax, the Type is an event name, and e2 is the reference of the listener. For
example, to remove the keyboard listener, the removeKeyListener() method will be called.
The source provides the methods to add or remove listeners that generate the events. For
example, the Component class contains the methods to operate on the different types of events,
such as adding or removing them from the listener.
Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners require two
things; first, it must be registered with a source; however, it can be registered with several
resources to receive notification about the events. Second, it must implement the methods to
receive and process the received notifications.
The methods that deal with the events are defined in a set of interfaces. These interfaces can be
found in the java.awt.event package.
For example, the MouseMotionListener interface provides two methods when the mouse is
dragged and moved. Any object can receive and process these events if it implements the
MouseMotionListener interface.
Types of Events
The foreground events are those events that require direct interaction of the user. These types of
events are generated as a result of user interaction with the GUI component. For example,
clicking on a button, mouse movement, pressing a keyboard key, selecting an option from the
list, etc.
The Background events are those events that result from the interaction of the end-user. For
example, an Operating system interrupts system failure (Hardware or Software).
To handle these events, we need an event handling mechanism that provides control over the
events and responses.
Design Goals
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
ActionListeners:
The Java ActionListener is notified whenever you click on the button or menu item. It is notified
against ActionEvent. The ActionListener interface is found in java.awt.event package. It has only
one method: actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.
The common approach is to implement the ActionListener. If you implement the ActionListener
class, you need to follow 3 steps:
1. component.addActionListener(instanceOfListenerclass);
1. import java.awt.*;
2. import java.awt.event.*;
3. //1st step
4. public class ActionListenerExample implements ActionListener{
5. public static void main(String[] args) {
6. Frame f=new Frame("ActionListener Example");
7. final TextField tf=new TextField();
8. tf.setBounds(50,50, 150,20);
9. Button b=new Button("Click Here");
10. b.setBounds(50,100,60,30);
11. //2nd step
12. b.addActionListener(this);
13. f.add(b);f.add(tf);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. //3rd step
19. public void actionPerformed(ActionEvent e){
20. tf.setText("Welcome to Javatpoint.");
21. }
22. }
Output:
MouseListener:
The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.
clicked on a component.
component.
3. mouseExited(MouseEventev): This method will get invoked when a Mouse is exiting a
component.
pressed on a component.
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample extends Frame implements MouseListener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e) {
16. l.setText("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e) {
19. l.setText("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e) {
22. l.setText("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e) {
25. l.setText("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e) {
28. l.setText("Mouse Released");
29. }
30. public static void main(String[] args) {
31. new MouseListenerExample();
32. }
33. }
Output:
The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified
against MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It
has two methods.
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
4. MouseMotionListenerExample(){
5. addMouseMotionListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),20,20);
15. }
16. public void mouseMoved(MouseEvent e) {}
17.
18. public static void main(String[] args) {
19. new MouseMotionListenerExample();
20. }
21. }
Output:
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three
methods.
Interface declaration
1. public abstract void keyPressed (KeyEvent e); It is invoked when a key has been pressed.
2. public abstract void keyReleased (KeyEvent e); It is invoked when a key has been released.
3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.
Methods inherited
o java.awt.EventListener
In the following example, we are implementing the methods of the KeyListener interface.
KeyListenerExample.java
Output:
Java WindowListener Interface
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.
The signature of 7 methods found in WindowListener interface with their usage are given below:
Sr. Method signature Description
no.
1. public abstract void windowActivated It is called when the Window is set to be an active
(WindowEvent e); Window.
2. public abstract void windowClosed It is called when a window has been closed as the
(WindowEvent e); result of calling dispose on the window.
3. public abstract void windowClosing It is called when the user attempts to close the
(WindowEvent e); window from the system menu of the window.
7. public abstract void windowOpened It is called when window is made visible for the first
(WindowEvent e); time.
In the following example, we are going to implement all the method of WindowListener
interface one by one.
WindowExample.java
Output:
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given below.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
In the following example, we are implementing the WindowAdapter class of AWT and one its
methods windowClosing() to close the frame window.
AdapterExample.java
Output:
MouseAdapterExample.java
Output:
Applet in Java:
An applet is a special kind of Java program that runs in a Java enabled browser. This is the first
Java program that can run over the network using the browser. Applet is typically embedded
inside a web page and runs in the browser.
In other words, we can say that Applets are small Java applications that can be accessed on an
Internet server, transported over Internet, and can be automatically installed and run as apart of a
web document.
After a user receives an applet, the applet can produce a graphical user interface. It has limited
access to resources so that it can run complex computations without introducing the risk of
viruses or breaching data integrity.
An Applet class does not have any main() method. It is viewed using JVM. The JVM can use
either a plug-in of the Web browser or a separate runtime environment to run an applet
application.
JVM creates an instance of the applet class and invokes init() method to initialize an Applet.
Note: Java Applet is deprecated since Java 9. It means Applet API is no longer considered
important.
Advantage of Applet
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is t
subclass of Component.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it
is for testing purpose only.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Graphics in Applet
Sr
Methods Description
No.
1 public abstract void drawString(String str, int x, int y) Used to draw specified string.
public abstract void fillRect(int x, int y, int width, int Used to draw a rectangle with a default
3
height) colourof specified width and height.
public abstract void drawOval(int x, int y, int width, int Used to draw oval of specified width and
4
height) height.
public abstract void fillOval(int x, int y, int width, int Used to draw oval with a default colour of
5
height) specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int Used for drawing lines between the point
6
y2) (x1, x1) and (x2, y2).
java.applet, java.awt and java.awt.image are the packages which are used for event handling.
Loading an image
In Applet, images are loaded using getImage() method. This method works when the constructor
of the Applet is called. It is always suggested to call the constructor in init() method.
Displaying an image
In Applet, images are displayed using drawImage() method. This method is supplied by the
Graphics object, which is passed to paint() method.
Example:
Aimage.java
import java.awt.*;
import java.applet.*;
Image img1;
img1=getImage(getDocumentBase(),"icon.png");
}
public void paint(Graphics g)
g.drawImage(img1,100,100,this);
<html>
</applet>
</html>
EventHandling in Applet
In Applet we can also perform event handling.
Below is an example of event handling which prints a message when clicked on the button.
Example:
EventAppletDemo.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
Button b1;
TextField tf1;
tf1=new TextField();
tf1.setBounds(30,40,200,20);
b1=new Button("Click");
b1.setBounds(80,150,60,50);
add(b1);
add(tf1);
b1.addActionListener(this);
setLayout(null);
tf1.setText("Welcome to studytonight");
Copy
Myapplet.html
<html>
<body>
</applet>
</body>
</html>
Animation in Applet
In Applet, we can also create animations in a program using a gif image. Below is an example in
which drawImage() method is used which is of Graphics class, it is used for displaying an image.
Example:
AnimationDemo.java
import java.awt.*;
import java.applet.*;
{
Image p;
p = getImage(getDocumentBase(),"ball.gif");
for(inti=0;i<500;i++)
try
Thread.sleep(100);
catch(Exception e)
{}
Difference between a Java Application and a Java Applet
Java Application is just like a Java program that runs on an underlying operating system with
the support of a virtual machine. It is also known as an application program. The graphical user
interface is not necessary to execute the java applications, it can be run with or without it.
Java Applet is an applet is a Java program that can be embedded into a web page. It runs
inside the web browser and works on the client-side. An applet is embedded in an HTML
page using the APPLET or OBJECT tag and hosted on a web server. Applets are used to
make the website more dynamic and entertaining.
The difference between Application and Applet:
Applications are just like a Java Applets are small Java programs that are
program that can be executed designed to be included with the HTML
independently without using the web document. They require a Java-
Definition web browser. enabled web browser for execution.
The “javac” command is used to Applet programs are compiled with the
compile application programs, “javac” command and run using either
which are then executed using the the “appletviewer” command or the web
Compilation “java” command. browser.
Applications can access all kinds Applets can only access browser-specific
of resources available on the services. They don’t have access to the
Access level system. local system.
Applets are loaded over the internet and they are prevented to make open network
connection to any computer, except for the host, which provided the .class file. Because
the html page come from the host or the host specified codebase parameter in the applet
tag, with codebase taking precedence.
They are also prevented from starting other programs on the client. That means any
applet, which you visited, cannot start any rogue process on you computer. In UNIX,
applets cannot start any exec or fork processes. Applets are not allowed to invoke any
program to list the contents of your file system that means it cant
invoke System.exit() function to terminate you web browser. And they are not allowed to
manipulate the threads outside the applets own thread group.
Applets are loaded over the net. A web browser uses only one class loader that?s
established at start up. Then the system class loader can not be overloaded, overridden,
extended, replaced. Applet is not allowed to create the reference of their own class
loader.
They cant load the libraries or define the native method calls. But if it can define native
method calls then that would give the applet direct access to underlying computer.