0% found this document useful (0 votes)
35 views

Notes Unit 4

The document discusses event handling in Java. It defines events and describes how they are generated and handled through listeners. It provides examples of common event classes and listener interfaces in Java and explains the process of registering sources with listeners to perform event handling.

Uploaded by

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

Notes Unit 4

The document discusses event handling in Java. It defines events and describes how they are generated and handled through listeners. It provides examples of common event classes and listener interfaces in Java and explains the process of registering sources with listeners to perform event handling.

Uploaded by

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

Event Handling in Java




An event can be defined as changing the state of an object or behavior 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
 Foreground Events
 Background Events

Types of 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.

Delegation Event Model

 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.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()

where Type represents the type of event.


Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.
Event Classes in Java
Event Class Listener Interface Description

An event that indicates that a


component-defined action occurred like
ActionEvent ActionListener
a button click or selecting an item from
the menu-item list.
Event Class Listener Interface Description

The adjustment event is emitted by an


AdjustmentEvent AdjustmentListener
Adjustable object like Scrollbar.

An event that indicates that a component


ComponentEvent ComponentListener moved, the size changed or changed its
visibility.

When a component is added to a


ContainerEvent ContainerListener container (or) removed from it, then this
event is generated by a container object.

These are focus-related events, which


FocusEvent FocusListener include focus, focusin, focusout, and
blur.

An event that indicates whether an item


ItemEvent ItemListener
was selected or not.

An event that occurs due to a sequence


KeyEvent KeyListener
of keypresses on the keyboard.

The events that occur due to the user


MouseListener &
MouseEvent interaction with the mouse (Pointing
MouseMotionListener
Device).

An event that specifies that the mouse


MouseWheelEvent MouseWheelListener
wheel was rotated in a component.

An event that occurs when an object’s


TextEvent TextListener
text changes.

An event which indicates whether a


WindowEvent WindowListener
window has changed its status or not.

Note: As Interfaces contains abstract methods which need to implemented by the


registered class to handle events.
Different interfaces consists of different methods which are specified below.
Listener Interface Methods

ActionListener  actionPerformed()

AdjustmentListener  adjustmentValueChanged()

 componentResized()
 componentShown()
ComponentListener
 componentMoved()
 componentHidden()

 componentAdded()
ContainerListener
 componentRemoved()

 focusGained()
FocusListener
 focusLost()

ItemListener  itemStateChanged()

 keyTyped()
KeyListener  keyPressed()
 keyReleased()

 mousePressed()
 mouseClicked()
MouseListener  mouseEntered()
 mouseExited()
 mouseReleased()

MouseMotionListene  mouseMoved()
r  mouseDragged()

MouseWheelListener  mouseWheelMoved()

TextListener  textChanged()

WindowListener  windowActivated()
 windowDeactivated()
Listener Interface Methods

 windowOpened()
 windowClosed()
 windowClosing()
 windowIconified()
 windowDeiconified()

Flow of Event Handling


1. User Interaction with a component is required to generate an event.
2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.
3. The newly created object is passed to the methods of the registered listener.
4. The method executes and returns the result.
.

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class Myevent extends Frame implements MouseListener{


int x=100,y=100;

String msg=" ";


public Myevent()
{
this.addMouseListener(this);
}

public void paint(Graphics g)


{
g.drawString(msg, x,y);

}
public static void main(String[] args)
{
Myevent f1=new Myevent();
f1.setSize(400,400);
f1.setVisible(true);
f1.setTitle("my first Frame");

}
@Override
public void mouseClicked(MouseEvent e) {
x=e.getX();
y=e.getY();
msg="mouse clicked at "+x + ","+ y ;
repaint();

}
@Override
public void mouseEntered(MouseEvent e) {

msg="mouse entered at ";


repaint();

}
@Override
public void mouseExited(MouseEvent e) {

msg="mouse exit at ";


repaint();

}
@Override
public void mousePressed(MouseEvent e) {
// x=e.getX();
// y=e.getY();
msg="mouse pressed at ";
repaint();

}
@Override
public void mouseReleased(MouseEvent e) {
// x=e.getX();
// y=e.getY();
msg="mouse re at released";
repaint();

Copying character from one file to another


import java.io.*;
public class copyfile {
public static void main(String[] args) throws IOException
{
File infile=new File("input.dat");
File outfile= new File("output.dat");
FileReader ins =new FileReader(infile);
FileWriter outs= new FileWriter(outfile);
int ch;
while((ch=ins.read( ))!=-1)
{
outs.write(ch);

ins.close();
outs.close();
}
}

 This program creates two objects infile and outfile and initializes them with ‘input.dat’ and
‘output.dat’

File infile=new File("input.dat");

File outfile= new File("output.dat");

 The program then creates two file stream object ins and outs and connect to the named file
using following code

FileReader ins =new FileReader(infile);

FileWriter outs= new FileWriter(outfile);

This connect infile to the FileReader stream ins and outfile to FileWriter Stream outs.

This means input.dat and output.dat files are opened.

 Ch= ins.read() reads a character from infile through the input stream ins and assigns it to the
variable ch. Similarly the statement outs.write(ch) writes the character stored in the variable ch
to outfile through the output stream outs. The character -1 indicates the end of the file and the
code

while((ch=ins.read( ))!=-1)causes the termination of the while loop when the end of file is reached.

 Statement Ins.close(); and Outs.close(); close the files created for readind and writing.

Output:
Note : first write some text in input.dat( which will appear in the program list).

Then run the program and check output.dat file in program list

LayoutManagers

The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in
GUI forms. LayoutManager is an interface that is implemented by all the classes of
layout managers. There are the following classes that represent the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout

Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another
(in a flow). It is the default layout of the applet or panel.

Constructors of FlowLayout class

1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

Example:

import java.awt.*;
public class flowlayout extends Frame
{
flowlayout(){
setLayout(new FlowLayout());
setSize(300,400);
setVisible(true);
Label l1= new Label("add");
Label l2=new Label("sub");
Label l3= new Label("mul");
Label l4=new Label("div");
add(l1);
add(l2);
add(l3);
add(l4);
}
public static void main(String[] args)
{
flowlayout fl=new flowlayout();
}
}

BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east,
west, and center. Each region (area) may contain one component only. It is the default
layout of a frame or window. The BorderLayout provides five constants for each region:

Constructors of BorderLayout class:

o BorderLayout(): creates a border layout but with no gaps between the


components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
o import java.awt.*;
o public class borderlayout extends Frame
o {
o
o borderlayout(){
o setLayout(new BorderLayout());
o setSize(300,400);
o setVisible(true);
o add(new Button("add"),BorderLayout.NORTH);
o add(new Button("sub"),BorderLayout.SOUTH);
o add(new Button("mul"),BorderLayout.WEST);
o add(new Button("div"),BorderLayout.EAST);
o add(new TextArea(),BorderLayout.CENTER );
o }
o public static void main(String[] args)
o {
o borderlayout bl=new borderlayout();
o }
o }
o

You might also like