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

Unit-Iv Event Handling

Uploaded by

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

Unit-Iv Event Handling

Uploaded by

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

UNIT-IV 1

Delegation Event Model:


The concept of delegation event model is: a source generates an event and
sends it to one or more listeners. The listener waits until it receives an
event, once received the listener processes the event and then returns.

In the delegation event model, listeners must register with the source to
receive an event notification.

Three points to notice here:

1. Events
2. Event Sources
3. Event listeners

UNIT-IV 2
Events:

An event is an object that describes a state change in a source.

Some activities that cause events to be generated are:


- pressing a button
- entering a character via keyboard
- clicking mouse
- selecting a checkbox …

UNIT-IV 3
Event Sources:
A source is an object that generates an event.

Source may generate more than one type of event.

A source must register listeners in order for the listeners to receive


notifications about the event.

UNIT-IV 4
Event Listeners:
A listener is an object that is notified when an event occurs.

Every listener has two requirements:


1. It must register with one or more sources.
2. It must implement methods to receive and process events.

UNIT-IV 5
Event Classes:

There are many events generated by many sources.


So, we begin with event classes:

At the root of Java event class hierarchy is EventObject class in java.util.


It is the superclass for all events.
It contains two methods:
Object getSource( )
String toString( )

The class AWTEvent in java.awt package is subclass of EventObject and is


superclass of all AWT-based events used by the delegation event model.

UNIT-IV 6
Event Classes:
The package java.awt.event defines several types of events generated by
various sources.

Event Class Description (Generated when)


ActionEvent A button is pressed, a list item is double clicked, menu selected
AdjustmentEvent Scroll bar is manipulated
ComponentEvent Component is hidden, moved, resized or becomes
visible
ContainerEvent Component is added to or removed from a container
FocusEvent Component gains or loses keyboard focus
ItemEvent Checkbox or list item clicked, choice selection is made
KeyEvent Input is received from the keyboard
MouseEvent Mouse is dragged, moved, clicked, pressed, released,
enters or exits a component
TextEvent Value in text area or text field is changed
WindowEvent Window is activated,
UNIT-IVclosed, deactivated, opened or quit
7
Event class hierarchies:

UNIT-IV 8
Event Source Classes:
Event Source Description
Button Generates action events when the button is pressed.
Checkbox Generates item events when the check box is selected or
deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked;
Generates item events when an item is selected or deselected.

Menu Item Generates action events when a menu item is selected;


generates item events when a checkable menu item is selected
or deselected.
Scrollbar Generates adjustment events when the scroll bar is manipulated.
Text Generates text events when the user enters a character.
components
Window Generates window events when a window is activated, closed,
deactivated, deiconified, iconified, opened, or quit.

In addition to these graphical user UNIT-IV


interface elements, other components,9
such as an applet, can generate events
Event Listener Interfaces:
Listeners are created by implementing one or more of the interfaces
defined by the java.awt.event package. When an event occurs, the event
source invokes the appropriate method defined by the listener and
provides an event object as its argument.
Interface
ActionListener
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
MouseWheelListener
TextListener
WindowFocusListener
UNIT-IV 10
WindowListener
Handling Mouse Events:

Event Sources Applet or Frame

Events MouseEvent

Event listeners MouseListener


MouseMotionListener

UNIT-IV 11
MouseEvent class: MouseListener interface:
int getX( ) void mouseClicked(MouseEvent me)
int getY( ) void mouseEntered(MouseEvent me)
Point getPoint( ) void mouseExited(MouseEvent me)
void translatePoint(int x, int y) void mousePressed(MouseEvent me)
int getClickCount( ) void mouseReleased(MouseEvent me)
boolean isPopupTrigger( )

MouseMotionListener interface:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)

UNIT-IV 12
Handling Mouse Events:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <applet code="MouseDemo" width=500 height=500>
</applet> */
public class MouseDemo extends Applet p v mouseExited(MouseEvent me) {
implements MouseListener msg="Exited";
{ repaint( );
String msg="Hello"; }
public void init( ) { p v mousePressed(MouseEvent me) {
addMouseListener(this); msg="Pressed";
} repaint( );
public void mouseClicked(MouseEvent me) }
{ p v mouseReleased(MouseEvent me) {
msg="Clicked"; msg="Released";
repaint( ); repaint( );
} }
public void mouseEntered(MouseEvent me) public void paint(Graphics g) {
{ g.drawString(msg,50,50);
msg="Entered"; }
repaint( ); }
UNIT-IV 13
}
Handling Key Events:

Event Sources Applet or Frame

Events KeyEvent

Event listeners KeyListener

UNIT-IV 14
KeyEvent class:

char getKeyChar( )
int getKeyCode( )

KeyListener interface:

void keyPressed(KeyEvent ke)


void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

UNIT-IV 15
Handling Key Events:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <applet code="KeyDemo" width=500 height=500>
</applet> */
public class KeyDemo extends Applet
implements KeyListener public void keyReleased(KeyEvent ke)
{ {
String msg="Hello"; msg="Released";
public void init() repaint();
{ }
addKeyListener(this); public void keyTyped(KeyEvent ke)
requestFocus(); {
} msg="Typed";
public void keyPressed(KeyEvent ke) repaint();
{ }
msg="Pressed"; public void paint(Graphics g)
repaint(); {
} g.drawString(msg,50,50);
}
UNIT-IV} 16
ActionEvent class: WindowEvent class:

String getActionCommand( ) Window getWindow( )


Window getOppositeWindow( )
AdjustmentEvent class: int getOldState( )
int getNewState( )
Adjustable getAdjustable( )
int getAdjustmentType( )
int getValue( )

ItemEvent class:

Object getItem( )
int getStateChange( )

UNIT-IV 17
ActionListener interface:
void actionPerformed(ActionEvent ae)
AdjustmentListener interface:
void adjustmentValueChanged(
AdjustmentEvent ae)
ItemListener interface:
void itemStateChanged(ItemEvent ie)
TextListener interface:
void textChanged(TextEvent te)
WindowListener interface:
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
UNIT-IV 18
Creating a Frame Window:

Define a class that inherits Frame class.


Create an object of the Frame subclass.
A frame will be created with default size and will not be visible.
Make the frame visible by calling setVisible( ) method.

Some methods of Frame class:

void setSize(int width, int height)


void setSize(Dimension dim)
void setVisible(boolean v)
void setTitle(String title)

UNIT-IV 19
Adapter Classes:
Adapter classes provides an empty implementation of all methods in an
event listener interface.
Adapter classes are useful when only some of the events are to be handled
by a particular event listener interface.

Adapter Class Listener Interface


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

UNIT-IV 20
Adapter Classes: Program to handle mouseclicked event
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <applet code="AdapterMouseDemo" width=500 height=500>
</applet> */
public class AdapterMouseDemo extends Applet
{
String msg="Hello"; class A extends MouseAdapter
public void init( ) { {
A obj1=new A(this); AdapterMouseDemo amd;
addMouseListener(obj1); A(AdapterMouseDemo amd1)
} {
public void paint(Graphics g) { amd=amd1;
g.drawString(msg,50,50); }
} public void mouseEntered(MouseEvent
} me)
{
amd.msg="Entered";
amd.repaint();
}
UNIT-IV 21
}
Adapter Classes: Program to handle keytyped event
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="AdapterKeyDemo" width=500 height=500>
</applet>
*/
public class AdapterKeyDemo extends Applet
{
String msg="Hello"; class A extends KeyAdapter
public void init() {
{ AdapterKeyDemo akd;
A obj1=new A(this); A(AdapterKeyDemo akd1)
addKeyListener(obj1); {
requestFocus(); akd=akd1;
} }
public void paint(Graphics g) public void keyTyped(KeyEvent ke)
{ {
g.drawString(msg,50,50); akd.msg+=ke.getKeyChar();
} akd.repaint();
} UNIT-IV } 22
}
AWT Controls:
Controls are components that allow a user to interact with our application.

The AWT supports the following types of controls:

• Labels
• Buttons
• Check boxes
• Choice lists
• Lists
• Scroll bars
• Text editing

All these controls are subclasses of Component class.

UNIT-IV 23
Component Class Hierarchy:

UNIT-IV 24
Adding Controls:
Steps to add a control to a container (Applet or Frame):

1. Create an instance of the desired control.


2. Add it to the container by calling the add method defined in Container class.
Component add(Component obj)
obj is the instance of the control.
Once a control is added, it will automatically visible on the container.

UNIT-IV 25
Removing Controls:

To remove a control, Container class defined a method:


void remove(Component obj)

UNIT-IV 26
Label:
Labels are passive controls that do not support any interaction with the user.

Label class Constructors: Methods:


Label( ) void setText(String str)
Label(String str) String getText( )
Label(String str, int how) void setAlignment(int how)
str is the text of the Label int getAlignment( )
how specifies the alignment
Label.LEFT
Label.RIGHT
Label.CENTER

UNIT-IV 27
Button:
A button (push button) is a component that contains a label and that generates
an event when it is pressed.

Button class Constructors:


Button( )
Button(String str)

Methods:
void setLabel(String str)
String getLabel( )

UNIT-IV 28
Checkbox:
A check box is a control that is used to turn an option on or off (check mark).
Each time a check box is selected or deselected, an item event is generated.
Checkbox class Constructors:
Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbg)
Checkbox(String str, CheckboxGroup cbg, boolean on)
Checkbox methods: CheckboxGroup methods:
void setLabel(String str) Checkbox getSelectedCheckbox( )
String getLabel( ) void setSelectedCheckbox(Checkbox
cb)
void setState(boolean on)
boolean getState( ) UNIT-IV 29
Choice:
The Choice is used to create a pop-up list of items.
Each time a choice is selected, an item event is generated.
Choice class contains only the default constructor.
Choice methods:
void addItem(String name)
void add(String name)
String getSelectedItem( )
int getSelectedIndex( )
int getItemCount( )
void select(int index)
void select(String name)
String getItem(int index)
UNIT-IV 30
List:
The List provides a compact, multiple-choice, scrolling selection list.
A list shows a number of choices in the visible widow. It also allow multiple
selections.

List constructors:
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)

List methods: String[ ] getSelectedItems( )


void add(String name) int[ ] getSelectedIndexes( )
void add(String name, int index) int getItemCount( )
String getSelectedItem( ) void select(int index)
int getSelectedIndex( ) String getItem(int index)
UNIT-IV 31
List:
Each time an item in the list is selected or deselected with a single click, an
item event is generated.
When a list item is double-clicked, an action event is generated.

UNIT-IV 32
Scrollbar:
Scrollbars are used to select continuous values between a specified minimum
and maximum.
Scrollbar constructors:
Style can be,
Scrollbar( )
Scrollbar.VERTICAL
Scrollbar(int style)
Scrollbar.HORIZONTAL
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
Scrollbar methods:
void setValues(int initialValue, int thumbSize, int min, int max)
int getValue( )
void setValue(int newValue)
int getMinimum( )
int getMaximum( )
void setUnitIncrement(int newIncr)
UNIT-IV 33
void setBlockIncrement(int newIncr)
TextField:
TextField is a single line text entry area. TexField is subclass of TextComponent.

TextField constructors:
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
TextField methods:
int getSelectionStart( )
String getText( )
int getSelectionEnd( )
void setText(String str)
void setEchoChar(char ch)
String getSelectedText( )
boolean echoCharIsSet( )
void select(int startIndex, int endIndex)
char getEchoChar( )
boolean isEditable( )
UNIT-IV 34
void setEditable(boolean canEdit)
TextArea:
TextArea is a multiline editor. TextArea is subclass of TextComponent.

TextArea constructors:
TextArea( )
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
TextArea(String str, int numLines, int numChars, int scrBars)

scrBars can be
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
UNIT-IV 35
TextArea:

TextArea methods:
String getText( )
void setText(String str)
String getSelectedText( )
void select(int startIndex, int endIndex)
boolean isEditable( )
void setEditable(boolean canEdit)
int getSelectionStart( )
int getSelectionEnd( )
void append(String str)
void insert(String str, int index)
void replaceRange(String str, int startIndex, ine endIndex)
UNIT-IV 36
Menu Bars and Menus:
Menus in Java are implemented by the use of the following classes:
MenuBar
Menu
MenuItem
CheckboxMenuItem

To create a menu bar, just create an instance on MenuBar class.


MenuBar class defines only the default constructor.

UNIT-IV 37
Menu:
Constructors:
Menu( )
Menu(String optionName)
Menu(String optionName, boolean removable)

MenuItem:
Constructors:
MenuItem( )
MenuItem(String itemName)
MenuItem(String itemName, MenuShortcut keyAccel)

UNIT-IV 38
CheckboxMenuItem:
Constructors:
CheckboxMenuItem( )
CheckboxMenuItem(String itemName)
CheckboxMenuItem(String itemName, boolean on)

MenuShortcut:

Constructors:

MenuShortcut(int key)

MenuShortcut(int key, boolean useShiftMidifier)

UNIT-IV 39
Layout Managers:
A layout manager is used by a container to position each of the components
with in it.
Each container has a layout manager associated with it.
A layout manager is an instance of any class that implements the interface
LayoutManager.
The layout manager is set by:
void setLayout(LayoutManager layoutObj)
Java defines the following layout manager classes:
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridbagLayout
UNIT-IV 40
FlowLayout:
FlowLayout is the default layout manager.
With this components are laid out from the upper-left corner, left to right and
top to bottom line by line.

Constructors:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
Valid how values are
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT

UNIT-IV 41
BorderLayout:
With BorderLayout, a conatiner has four narrow fixed-width components at
the edges and one large are in the center. The four sides are referred to as
north, south, east and west. The middle area is called the center.

Constructors:
BorderLayout( )
BorderLayout(int horz, int vert)
To add components use the following add method:
void add(Component compObj, Object region)
The region can be
BorderLayout.CENTER
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
UNIT-IV 42
BorderLayout.SOUTH
GridLayout:
GridLayout lays out components in a two-dimensional grid.

Constructors:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)

UNIT-IV 43
CardLayout:

Constructors:
CardLayout( )
CardLayout(int horz, int vert)
To add cards to a panel:
void add(Component panelObj, Object name)
Methods:
void first(Conatiner deck)
void last(Conatiner deck)
void next(Conatiner deck)
void previous(Conatiner deck)
void show(Conatiner deck, String cardName)

UNIT-IV 44
GridbagLayout

Sometimes we need a tabular arrangement(Grid) of the components where


columns have different sizes or one component spans multiple columns. To
handle these situations, a complex layout manager called GridbagLayout is
used.

UNIT-IV 45
Canvas:

A Canvas component represents a blank rectangular area of the screen


onto which the application can draw or from which the application can
trap input events from the user.

An application must subclass the Canvas class in order to get useful


functionality such as creating a custom component. The paint method
must be overridden in order to perform custom graphics on the canvas.

public Canvas( )

public void paint(Graphics g)

UNIT-VII
UNIT-IV 46
Dialog Boxes:

Dialog boxes are similar to frame windows, except that dialog boxes are
always child windows of a top-level window. Also, dialog boxes don’t have
menu bars.
Dialog boxes may be modal or modeless.
Constructors of Dialog class:
Dialog(Frame parentWindow, boolean mode)
Dialog(Frame parentWindow, String title, boolean mode)

UNIT-IV 47

You might also like