Event Handling in Java in Unit 5

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

UNIT-5

Event Handling in Java

An event can be defined as changing the state of an object or behaviour by performing


actions. Actions can be a button click, cursor movement, keypress through keyboard or page
scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
1. Foreground Events
2. Background Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground
events are generated due to interaction by the user on components in Graphic User Interface
(GUI). Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor
moments, etc.

2. Background Events
Events that don’t require interactions of users to generate are known as background events.
Examples of these events are operating system failures/interrupts, operation completion, etc.

Event Handling: It is a mechanism to control the events and to decide what should happen
after an event occur. To handle the events, Java follows the Delegation Event model.

Delegation Event model


It has Sources and Listeners.
Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to generate
events.
Listeners: Listeners are used for handling the events generated from the source. Each of these
listeners represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.
The java.awt.event package provides many event classes and Listener interfaces for event
handling.
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
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:
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){}

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

1. Within class
2. Other class

Example:
import java.awt.*;  
import java.awt.event.*;  
class AEvent extends Frame implements ActionListener{  
TextField tf;  
AEvent(){  
  
//create components  
tf=new TextField();  
tf.setBounds(60,50,170,20);  
Button b=new Button("click me");  
b.setBounds(100,120,80,30);  
  
//register listener  
b.addActionListener(this);//passing current instance  
  
//add components and set size, layout and visibility  
add(b);add(tf);  
setSize(300,300);  
setLayout(null);  
setVisible(true);  
}  
public void actionPerformed(ActionEvent e){  
tf.setText("Welcome");  
}  
public static void main(String args[]){  
new AEvent();  
}  
}  
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the
above example that sets the position of the component it may be button, textfield etc.
In Java, a frame is a window that has nice borders, various buttons along the top border,
and other features.
Frame is a container object, so GUI components can be placed in it.
Example 2:
import java.awt.*;  
import java.awt.event.*;  
class AEvent2 extends Frame{  
TextField tf;  
AEvent2(){  
//create components  
tf=new TextField();  
tf.setBounds(60,50,170,20);  
Button b=new Button("click me");  
b.setBounds(100,120,80,30);  
//register listener  
Outer o=new Outer(this);  
b.addActionListener(o);//passing outer class instance  
//add components and set size, layout and visibility  
add(b);add(tf);  
setSize(300,300);  
setLayout(null);  
setVisible(true);  
}  
public static void main(String args[]){  
new AEvent2();  
}  
}  
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
Listener Interface Methods
ActionListener  actionPerformed()
AdjustmentListener  adjustmentValueChanged()
ComponentListener  componentResized()
 componentShown()
 componentMoved()
 componentHidden()
ContainerListener  componentAdded()
 componentRemoved()
FocusListener  focusGained()
 focusLost()
ItemListener  itemStateChanged()
KeyListener  keyTyped()
 keyPressed()
 keyReleased()
MouseListener  mousePressed()
 mouseClicked()
 mouseEntered()
 mouseExited()
 mouseReleased()
MouseMotionListener  mouseMoved()
 mouseDragged()
MouseWheelListener  mouseWheelMoved()
TextListener  textChanged()
WindowListener  windowActivated()
 windowDeactivated()
 windowOpened()
 windowClosed()
 windowClosing()
 windowIconified()
 windowDeiconified()

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.
Methods of KeyListener interface
S.No Method name Description
1. public abstract void keyPressed (KeyEvent e); It is invoked when a key has been pressed.
2. public abstract void keyReleased (KeyEvent It is invoked when a key has been
e); released.
3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.

Example:
// importing awt libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits Frame class and implements KeyListener interface
public class KeyListenerExample extends Frame implements KeyListener {
// creating object of Label class and TextArea class
Label l;
TextArea area;
// class constructor
KeyListenerExample() {
// creating the label
l = new Label();
// setting the location of the label in frame
l.setBounds (20, 50, 100, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
area.setBounds (20, 80, 300, 300);
// adding the KeyListener to the text area
area.addKeyListener(this);
// adding the label and text area to the frame
add(l);
add(area);
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// overriding the keyPressed() method of KeyListener interface where we set the text of the
label when key is pressed
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
// overriding the keyReleased() method of KeyListener interface where we set the text of the
label when key is released
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
// overriding the keyTyped() method of KeyListener interface where we set the text of the
label when a key is typed
public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
// main method
public static void main(String[] args) {
new KeyListenerExample();
}
}

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.
Methods of MouseListener interface
1. public abstract void mouseClicked(MouseEvent e);  
2. public abstract void mouseEntered(MouseEvent e);  
3. public abstract void mouseExited(MouseEvent e);  
4. public abstract void mousePressed(MouseEvent e);  
5. public abstract void mouseReleased(MouseEvent e);  
Example
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
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");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
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.

Advantages of Adapter classes:


 It assists the unrelated classes to work combinedly.
 It provides ways to use classes in different ways.
 It increases the transparency of classes.
 It provides a way to include related patterns in the class.
 It provides a pluggable kit for developing an application.
 It increases the reusability of the class.

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.

 java.awt.event Adapter classes

Adapter class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener

 java.awt.dnd Adapter classes

Adapter class Listener interface

DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
 javax.swing.event Adapter classes

Adapter class Listener interface

MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener

In the following example, we are implementing the Mouse event handling which creates
frame and by mouse clicks it creates circles in blue color
Example:
Import java.awt. *;
Import java.awt.event.*;
Public class Example extends Frame implements MouseListener
{
Example () {
super (“Mouse Listener”);
addMouseListener(this);
setSize(300,300);
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 mouseReleased(MouseEvent e){}
Public void mousePressed(MouseEvent e){}
Public void mouseExited(MouseEvent e){}
Public static void main (String a[]){
New Example ();
}
}
In the above example we have to override all the abstract methods of MouseListener interface
but when we use adapter class no need to override all of the methods.
Example:

Import java.awt. *;
Import java.awt.event.*;
Public class ExampleAdapter extends MouseAdapter
{
Frame f;
Example () {
f=new Frame(“Mouse Adapter”);
addMouseListener(this);
setSize(300,300);
setVisible(true);
}
Public void mouseClicked(MouseEvent e){
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
Public static void main (String a[]){
New ExampleAdapter ();
}
}
AWT- Abstract window toolkit
Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).
Java AWT calls the native platform calls the native platform (operating systems) subroutine
for creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have
different look and feel for the different platforms like Windows, MAC OS, and Unix. The
reason for this is the platforms have different view for their native components and AWT
directly calls the native subroutine that creates those components.
Characteristics
 It is a set of native user interface components.
 It is very robust in nature.
 It includes various editing tools like graphics tool and imaging tools.
 It uses native window-system controls.
 It provides functionality to include shapes, colors and font classes.
Advantages
 It takes very less memory for development of GUI and executing programs.
 It is highly stable as it rarely crashes.
 It is dependent on operating system so performance is high.
 It is easy to use for beginners due to its easy interface.
Disadvantages
 The buttons of AWT does not support pictures.
 It is heavyweight in nature.
 Two very important components trees and tables are not present.
 Extensibility is not possible as it is platform dependent
Java Swings
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing
Java AWT Java Swing

AWT components are platform-dependent. Java swing components are platform-


independent.
AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.
AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
AWT doesn't follows MVC(Model View Controller) Swing follows MVC.
where model represents data, view represents
presentation and controller acts as an interface between
model and view.

Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int sets size of the component.
height)
public void setLayout(LayoutManager sets the layout manager for the component.
m)
public void setVisible(boolean b) sets the visibility of the component. It is by
default false.
The methods of Component class are widely used in java swing that are given below.
There are two ways to create a frame:
 By creating the object of Frame class (association)
 By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
MVC architecture of Java Swing
Swing architecture is rooted in the model-view-controller (MVC) design that dates back to
SmallTalk . MVC architecture calls for a visual application to be broken up into three
separate parts:
 A model that represents the data for the application.
 The view that is the visual representation of that data.
 A controller that takes user input on the view and translates that to changes in the
model.
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.

Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.
Example:
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Java Swings.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Example of displaying image on the button
import javax.swing.*;
public class ButtonExample{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\icon.png"));
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample();
}
}
Example for Jlable
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

Applet: An applet is a Java program that can be embedded into a web page. It runs inside the
web browser and works at client side.
Advantage of Applet
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
 Plugin is required at client browser to execute applet.
Rules for Java Applets
1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
2. Applets are not stand-alone programs. Instead, they run within either a web browser
or an applet viewer. JDK provides a standard applet viewer tool called applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather it is
handled with various AWT methods, such as drawString().
Life Cycle of Servlet

It is important to understand the order in which the various methods shown in the above
image are called. When an applet begins, the following methods are called, in this sequence: 
1. init( )- The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your
applet.
2. start( )- The start( ) method is called after init( ). It is also called to restart an applet
after it has been stopped. Note that init( ) is called once i.e. when the first time an
applet is loaded whereas start( ) is called each time an applet’s HTML document is
displayed onscreen. So, if a user leaves a web page and comes back, the applet
resumes execution at start( ).
3. paint( )- The paint( ) method is called each time an AWT-based applet’s output must
be redrawn. This situation can occur for several reasons. For example, the window in
which the applet is running may be overwritten by another window and then
uncovered. Or the applet window may be minimized and then restored.
When an applet is terminated, the following sequence of method calls takes place: 
1. stop( )- The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page, for example. When stop( ) is
called, the applet is probably running. You should use stop( ) to suspend threads that
don’t need to run when the applet is not visible. You can restart them when start( ) is
called if the user returns to the page.
2. destroy( )- The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free
up any resources the applet may be using. The stop( ) method is always called before
destroy( ).
Example of Applet
import java.applet.Applet;
import java.awt.Graphics;
 
// HelloWorld class extends Applet
public class HelloWorld extends Applet
{
    // Overriding paint() method
    @Override
    public void paint(Graphics g)
    {
        g.drawString("Hello World", 20, 20);
    }
     
}

Passing Parameters to applet


Parameters specify extra information that can be passed to an applet from the HTML page.
Parameters are specified using the HTML’s param tag.
The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two
attributes: name and value which are used to specify the name of the parameter and the value
of the parameter respectively. For example, the param tags for passing name and age
parameters looks as shown below:
<param name=”name” value=”Divya” />
<param name=”age” value=”25″ />

Now, these two parameters can be accessed in the applet program using
the getParameter() method of the Applet class.

The getParameter() method of the Applet class can be used to retrieve the parameters passed


from the HTML page. The syntax of getParameter() method is as follows:

Example
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name"); Parameter reading using method
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" /> Parameters passed
<param name="age" value="25" /> using tags
</applet>
*/

You might also like