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

Java Last Unit 3

Uploaded by

reherow
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Java Last Unit 3

Uploaded by

reherow
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

300 A Functional Approach to JAVA OOP Foundations

4. Add (Compone nt c, int zone) method is used to add any componen t to the container.
5. Zone argument may be one of the following-
(i) BorderLay out.NORTH (ii) BorderLay out.SOUTH
(iii) BorderLay out.EAST (iv) BorderLay out.WEST
(v) BorderLay out.CENTE R
6. Border layout can be created by using one of the following constructor .
Construct ors of Border Layout Class :
S.No.
1.
Constructors
BorderLayo ut()
S.No.
1.
Description s
It creates a new border Layout
--
2. BorderLayo ut(int hgap, intVgap) 2. It creates a new border layout with a horizonti
gap ofhgap and vertical gap of Vgap.
Methods of BorderLay outClass : -
S.No. Methods S.No. Description s
1. setHgap(int hgap) 1. It sets or changes the current horizontal gap to hgap.
2. getHgap() 2. It returns the current horizontal gap.
3. setVgap(int Vgap) 3. It sets or changs the current vertical gap to Vgap
4. getVgap() 4. It returns the current vertical Gap.

PROGRA M 13.14: Program to show the arrangement of componen ts using Border Layout Manager.
Step I : Code for border.java
bon!er,java - Notepad
F,!e Edn Format Vlf:W Help

import java.awt.*; r
import Java.applet .#;
public class border extends Applet
{
public void init()
{
BorderLayou t b=new BorderLayo ut();
this.setlay out(b);
Button buttonl=new Button !"Buttoi:il "l;
l
E
Button button2=new Button "Button2" ;
Button button3=new Button "Button3" ;
Button button4=new Button "Button4" ;
Button buttonS=new Button "Buttons" ·
this.add!but tonl,Border layout.CEN TER;;
th,s.add button2,Bord erLayout.NO RTH)·
this.add button3,Bord erLayout.SO UTH):
this.add button4,Bor derLayout.E AST)·'
this.add buttonS,Bor derLayout.W EST);
}
}

Fi9. :1.3.:1.8(t:t)
Step 2 : Code for border.htm l
border.html · Notepect
File Edit Format View

<HTML>
<BODY>
<APPLET code="border"
w;dth=200
he;ght-100 >
</APPLET>
</BtJOY>
</HlML>
301
AW T
ChaPter I3 - GUI Prog ram min g with
Step 4 : Output
. com pile and Run the pro gra m
steP 3 •

--
.oom -
r ~
~

IIIIDn5
llllllln2

IMIDn1 .....
IMIDn3
1AN1111111111e1.
Fig. J.3.J.B(d)
F 9 :L3 :LS( c)
out.
also specified its zon e in the Bor der Lay
In this program,,~ c add ed fh c hut ton and

(4) Card Layout com pon ents


man age rs as it can stor e two or mor e
Card La)O llt managt:r 1s diff eren t from oth er layout
we can see onl y
one of them at a lime . It arra nge s all the con tain ers as stac k of card s and
illd displa) onl) we can see
exa mpl e In MS Exc el, a wor k boo k con tain s a num ber of wor ksh eets but
one card at a tune. For
only one of them hr chc kmg on the shee t tab.
com pon ents
man age s the com pon ents in a sequ ence. We can display the nex t or prev ious
The card La) out com pon ents .
a uniq ue nam e to con trol the display of
by sending ttquest. We can give com pon ent
can add any num ber of com pon ents
by usin g the following met hod :
We
ad (St r ng n pon ent c);

Conatructon of Canll.ayout Ciu s:

I. 1. It creates a new Car d Layout


Card .Lay out( )
2. It creates a new Card
2. Cudl.a)"OUt (int bpp . int Vpp ) horizontal and Vertical Gap.
302
A Jlunctional Approach to JAVA OOP roundat· ~
< IOn\

PR.OGRAM 13.15: Program to show the arrangement of components in Card Layout Mana
Step l : Code for card.java ge.,,

File Ed,t form•t '✓•• , Help


import java.awt.*;
import lava.applet.*;
import Java.awt.event.*; r
~ublic class card extends Applet implements Act·,
CardLayout c;
Panel pl,p2,p3;
Button buttonl,button2;
public void init()
{
c=new Cardlayout();
buttonl=new Button("Next");
button2=new Button("Previous");
pl=new Panel ();
p2=new Panel();
pl.setlayout(c~;
pl. add~buttonl ;
p2.add button2;
pl. add p2, "cardl");
add(pl);
buttonl.addActionListener(this);
button2.addActionListener(this);
}

//Event Handlin~
RUblic void act1onPerformed(ActionEvent e)
{
if(e.getsource()=buttonl)
{
c.next(pl);
c.show(pl,"Card 2");
}
else if(e.getSource()=button2)
{
c.previous~pl);
c.show(pl,'Card 1");

Step 2 : Code for card.html


card.html • Notepad :-::::::::;::~~~~_'!
file Edit format View Help

<HTML>
<BODY>
<APPLET code-"card"
width=150 E
height=150>
</APPLET>
</BODY>
</HTML>

Fi9. :1.3.20(b)

Step 3 : Compile and Run the program

ffr C:\Wlndows\system32\oommand.com I • , I l:"J ~J

D: PROGRAMS>javac card.java ...


D: PROGRAMS>appletviewer

.
card.html
.
ps;

... ◄ I ,. ·~

Fi'g. l-3 l-Cf(c)


•:;,

--
GUJ ProgrammJllg wirll AW
T
a,,prer13
_, ,, = ouq,ut n -

,,,,. ;::....- !

~__,
-

--,,._ '4,
' ,.,. T

-. - • I
,..-

Fig. J.3 J.4'(e)


3 d l Pl
PI an d P2 an d ad d on e bu tton with each panel Pane
ated two panel nel Pl is
In tht abo"e pr r m we cre 2 i e , pr m om W hm the applet is started, only Pa
P2 h butto n s invisible
t,utton 1 1 e Next and P nd ck the N at Bu tton of Panel I. Panel I become
d) Whe n we cli neJ 2. PaneJ 2
~y td on reen I e I 1g 11 19( playe d W hen we clJdc 'Pr mo u, ' Button of Pa
wi ll be dis
and Panel 2 will Prevmu Button
l J w 1IJ ~ di played
l,tcOllltS m,1 1bit and Pane an the program.
~ pand to the da ck C\'t'nt we use Evmt Handling
To control and
(S) G,WBagLayout s and co)IIIDIII.
ut arran ge s the co mp on mt s of container in a gri d ofrow
yo Layout. Grid Bag.Layout div
lc:le,
Liu Grad Layout Gm / Bag l.a vided by AW T is Grid Ba g
1ht most fte.11blt and complex
layout M an aF r pro
on ents an multiple l'OWI and co
lumm. 1he
can org an au comp
IISconwntr mto an array
of flexjble al ls We
of dHfermt columns can ha
ft cWFetat wlddJ.
en t he ights an d the cells
ddfer
mlsol diferent rows can have
C111l1iiClllf!6Gdd . . .
J. .,. .a O ... :
ODDlll'uctof.
Gddllla
304 \ him tio11.1l i\pproa1.:h ln J/\VA 001' l·ounda llon~

E..'\.1llllpk :
1..~'l:1 .dl~hc, ,n.,t[dl lltS. g11d:< 2;
Cl1dB 1q~0n strd1n ls . gridy - 2;
~- f_rid";dth, gridhe ight : The grid width and grid height constr
aint~ are used to control the size of
mron~ nt A con1ponent ma)' use one or more cells. So we can create
,\ -.'.\.1
. . different layout by specify•
. . . b
numb1.:'r$ ot cells in a row for grid width or colum n for gndhe 1ght as given e1ow .· ing the
Exam ple:
GridB agCon strain ts . gridw idth = 3;
GridB agCon strain ts .gridh eight = 4;

3. Fill: Fill is used to determine wheth er a compo nent fill the availab
le space either horizontally, Verticall
or both. Fill is used when the compo nent's display area is larger than
the compo nent size. y
Const ants used :
1. Grid.Bag Constr aints. NONE (By default)
2. GridB ag Constr aints. HORIZONTAL
3. Grid.Bag Constr aints. VERTICAL
4. Grid.Bag Constr aints. BOTH
GridB agCon strain ts.HO RIZO NTAL changes the width of compo
nent so that it fills the components
displa y area horizontally. But it does not changes it height.
GridB agCon strain ts.VER TICA L : Changes the height of compo
nent so that it fills the component's
displa y area vertical. But It does not change its width.
GridB agCon strain ts BOTH : changes the width and height of the
compo nent so that the component's
displa y area fills entirely.
4. ancho r : The anchor is used to contro l the positio n of cell. It is
used when the size of component is
smalle r that its display area ancho r is an integer value that can use
the following consta nts :
(i) GridB agCon straint s.CEN TER (Bydefault)(ii) GridB agCon straint
s.NOR TH
(iii) GridB agCon straint s.NOR THEA ST (iv) GridB agCon straint s.EAS T
(v) GridB agCon straint s.SOU THEA ST (vi) GridB agCon straint s.SOU TH
(vii) GridB agCon straint s.SOU THWE ST (viii) GridB agCon straint s.WES T
(ix) GridB agCon straint s.NOR THWE ST
5. ipadx, ipady : ipadx and ipady is used to specify the compo nent's
intern al paddi ng within the layout.
It define s how much to add to the minim um size of the compo nent.
Atleast, the ,-vidth of the compo nent will be
minim um width of the compo nent+ (ipadx*2) pixels
Atleast, the height of the compo nent will be
minim um height of the comp onent + (ipady*2) pixels.
6 - insets : insets is used to specify the extern
al paddi ng i.e., the minim um space betwe en the component
and the edges of the compo nent's display area. The inset setting takes
a java.a wt.ins ets object as its value. B)
default, the inset space is left blank so that it can be used to define
a borde r or title.
7 · weightx, weighty : weightx, weight
y is used to stretch rows and colum ns. It is not used for individual cells-
lt all th e colum ns have value O and only one has value 1.0, then the
the maxim um available space. one that has value 1 will st retch 10

¼'e can define the values as given below :


Example:
r
GUI Programming with AWT
ch•P"' 13- 305
jJJ . . to show the arrangement using GridBagLayout Manager.
: program
13 16
ylloG~code for gridbag.Java
5teP 1.

import java.awt.~; •·
import 3ava.applet. ,
P.ublic class gridbag extends Applet
{ ~ublic void init()
{ Label ll=new Label("Himanshu Garg");
sutton bl==new Button("OK");
Gri dsageons trai nts gbc=new Gri dsageons traints () ·
GridBagLayout gbl=new GridBagLayout(); '
Frame f=new Frame("New Frame");
f.setsize(200,100);
f.setLayout(gbl); r
gbc.gridx=O;
gbc. gridy=O;
gbc.weightx=150;
gbc.fill=GridBagConstraints.HORIZONTAL;
f.add(ll,gbc);
gbc.fill:GridBagConstraints.V~RTICAL;
gbc.gridheight=3;

u
gbc. we~ ghtx=2 5; .
gbc. gn dx-+-+;
f.add(bl,gbc);
f.setvisible(true);
}
}

Fig. j.3.:Z.O(a)

Step 2 : Code for gridbag.html


_, gridbag,html - Notepad
f'ile . Ecfrt forrn,t Vi- Help

<HTI4L>
<APPLET code= "gr,'db a9
<BODY> II
=
width=250
height:250>
</APPLET>
</BODY>
</HTML>

Fig. j.3.:Z.O(b)

5tep 3 : Compile and Run the program

~ C:\WI nows
d \system32\command com
= @J ~

.
D:\PROGRAMS>javac
gridbag. java
-
D:\PROGRAMS>appletviewer gridbag.html

...

l
◄ lit

Fig. 3-3.:w(c)
A Functional Approach to JAVA OOP Foundations
306

Step 4 : Output
f:! __ _ _ _ O X

Al>f)let

11:} ~Fra- I 0 ! El 1l

H1mansnu Garg

At)plet started

Fi9. :n .20( d)

In the above program, we added one label with text "Himanshu Garg'' and one button with title "OK"
to the frame having title "New frame': We used GridBag Constrainsts to customize these components and
arranged them using GridBagLayout Manager.

i11MIM:i;tlil
----------------------------------------------------------------- -------·---
..- Java provides a class library known as Abstract Window Toolkit (AWT). It i-. platform independent and create applets as well
as stand alone applications that run in GUI environment.
..- AWT consists of 12 packages. These packages contain a number of AWT classes that are used in GUI programming. The
core AWT classed are contained in the java.awt package. The most commonly used packages are-
1. java.awt package
2. java.awt.event package
.,,, Components and container are the main AWT classes. Component is an abstract class that encapsulates all the attributes of a
visual component. It is at the top of AWT hierarchy. It supports a variety of graphical elements such as Labels, Buttons, Text
field, TextArea, CheckBox etc.
Container is used to hold components. The container class is a subclass of component.

.,,, Subclasses of container class are-


Window, Panel-subclasses of Container Class
Frame, Dialog - Subclasses of Window Container class.
Window c:teate6 a IX>p level window on the screen without title bar and menu bar.

....
~-
Fr"1M Is a 811.ia ll'indow for Applets and stand alone applications which bas a tide bar, an optional menu bar and C()l2tent

wcamgroupvariOUS ~
AWT components-
. Chanter 16

EVENT CLASSES

16.1 EVENT CLASSES

J,wa provides us v,\rious L'Vcnt classes lo represent l he events. 'Ihese event classes are at the core ofJav ,
c..'\'c..'nt handling tnl.'chauism. 'lhus, a discussion of event handling must begin with the event classes, 1h:s
pnwic..k ,1 consisknt and casy to usc means of encapsulaling events. Java defines several types of events b!t
we will dis1.·uss thosl.' event classes in this chapter which arc more frequently used.

. . . .. .. . Event
16.1.1 . .. .
Object Class
. .... ....... ...

Evc-nt ob_ject dass is the root class of the Java event class hierarchy from which all event state objects
shall be derived. It is the superclass for all events. 'fois class is defined in java. util package.
Class declaration :
TI1e dedarntion forjavn.util. Event object class is as follows:
public class Event Object
extends object
impleme n ts serializable
Field:
TI1e field for Jaw1.11til. Event object class are as follows:
p rote ct e d object source

The object on v,rhich the event initially occurred.


Class Constructors :
One constructor of event object class is shown here
Event Object (object source)

Here, source is the object that generate this event.


It constructs a prototypical Event.
Class Methods :
Event object class contains two methods :
1. get source()
2. to string()

S.No. M.tho4
1 getsource( ) Dam tion General for"!.
This method returns the source of the event. It object getsource( )
represents the object on which the event initially
occurred.
2 toString( )
Thia method return, the string equivalent of this stringtostring( )
_ Event Cla~,e,; 335
chapter J6

£VENT CLASSES
,, 14'/'ff · · 1 ss is defined within the 1ava.awt package.
A6,~
> · 4e AW' '
J"

paC
'(f.Vel'll C a
. v,i aw1.c
J<,tge J" ·
b sevcra
vent defines vanous types of events that
I user mtcrface elements It 1s a subclass of I
·M•i•,
- •_;,a-x•:__
1ne nerated Y cla 5 of all AW r ba ed events u~ed by the
.,ege t but super ,,,_,,-,.C,110.,,,.,dauofoll..,.,.,._
_. ob•ec nt Mode I
f,,ent i
cga11° 0 f,H blc -;howlng the n.m1c of mo t frequently
A.WT,,,_,,., a_,,,.,
dau ol all A.wr _.,.
D'l , llo" ,ng I .1 1 fttot ere handled by ,,_ Delegation Event
'f11c •0 I Jm ",de a brief d cnption as oc1ated
1 J,1 <,C<; JJH1• O Model, - .,;a dudy lofw.
d t"ctl
1
h main J \cnl da In ;ma awt ever,t are a,;
u,t aJlll c
1he1r o
,,11h
folJOI\~
,,,,,,<111 Ducrlpllon
It I o< t <'.'le of II AWT evcnl'>. This class and all 11s subclasses
u th ori m I 1ava
It wh n ,1 butt 1st item is double clicked or a menu
Adi< nf Hill
2 d
ntl , nt It I
; Ad
nt I , nt It I wh n a c.ompo med res1ud, hidden or becomes v1s1ble.
.. (o I
lh I c.l rcprc nt cm stock of a window.
111 omponcnt I
5 rcprc nt t state of a window.
hx.U l:HOI 11 g ncr tc-d when a component g.iins or lo keyboard focus.
6
11 t r , t C\ nl d for all wmponc-nt IC'\el mput c-,rent classes.
In uth , t
lteml ,e t It I
-------------i
ncr tcd '1ihcn ~he k menu 1tc-m (check box or list Item etc.) 1s selected or
8
cl Ice too or d1 kcd
.~~~----
111 gcnc:r ted ~hen am input is rcccwed lrom the keyboard.
------'-----------!
10 Mou hcnt It I gcncr ted \\hen the mou~ ts clicked released moved or dragged and also
ncratc:d ,,hen the mouse actions occurred (enters or exits) ma componc-nt.
11 It t c1 crated \\ hen the mouse wheel 1s moved. (This Event class 15 added by
J \ 2 \er wn l 4)
12 It I
---
generated \\ hen the \"alue of text field or text area 1s entered or changed.
13 It ts gener.:atcd when a w,ndo"' 1s opened. actJ, ated, icomfied, closed, deactivated.
detcamfied or quu Inc obJect of this class represents the change in state of a
\\tndO\\

(I) AWTEvent class: 1he A\\ Tfaent classes represent the event. It is the root class from which all
C\'n!t statr obJ«ts shall bedenved.
Wr have studied this detailed m the begmnmg of this topic 1.e. Event classes.
~l) The ActionEvent dus: The Act1onfaent 1s generated when a button is pressed, a list item is double
or a menu lS selected.
1he ActionEvent class defines these 5 integer constants:

Daaiplion
1bese 4 integer constants are used to identify any
modifies associated with an action evenL

1bis is an integer constant which can be used to


idcutift .ction evmts.
336 A Functional Approach to JAVA OOP Fo d .
un at1ons
ActionEv ent has three construc tors :
S.No. Construct or Descripti on
1. ActionEv ent (Object src, int Generated event with specified type of the event
type, string cmd) its comman d stnng . cm d .
. 1s and
2. ActionEv ent (Object src, int Generated event with specified type of the evenld
type, string cmd, int modi- its command string is cmd and modifier keys (A~;
fiers) CTRL, META, and/or SHIFT) '
3. ActionEv ent (Object src, int Generated event with specified type of the event and
type, string cmd, long when, its command string is cmd, when and modifier keys
int modifiers) (ALT, CTRL, META and/or SHIFT)

Here, -
src is a reference to the object that generate d this event.
type is used to represent the type of the event.
cmd is its comman d string.
modifiers argumen t indicates which modifier keys.
(ALT, CTRL, META and/or SHIFT) were pressed when the event was gen
erated.
when paramete r specifies when the event occurred .

The third constructor was added by Java2 version 1 .4.

ActionEv ent has these methods :


S.No. Method Descriptio n Syntax
1. getAction Comman d() It is used to obtain the command name for string getAction command( )
the invoking Action event object.
2. getModifi ers( ) It returns a value that indicates which int getModifi ers( )
modifier keys (ALT, CTRL, META and/or
SHIFT) were pressed when the event was
generated .
3. getWhen () It returns the time at which the vent took long getWhen( )
place.

The getWhen( ) method is called the event's timestampe. Timestamps


were added by ActionEvent to help support the improved input focus
subsystem implemented by Java2 version 1.4.

(3) The Adjustm ent Event class:


The Adjustm ent Event is generate d when a scroll bar is manipula ted
d
.
Adjustm ent Event class has 5 types of adjustment events. It defines integer h an be use
constants t at '
to identify them.
6 _ Event Classes 337
chapter 1
Constants Description
. ase its. value
BLOCK_INCREMENT The user clicked inside the scroll bar to mcre
Th e user clicked ins·1de th e scroll bar to decrease its value·
BLOCK_DECREMENT
·
The slider was dragged.
rRACK
ed to increase
lJNJT_INCREMENT !hte blutton at the end of the scroll bar was click
4. 1 s va ue.

d to decrease
!he blutton at the end of the scroll bar was clicke
its va ue.
· d'1cates that a
NGED th at m
·o·on there is an integer constant, ADJUSTMENT- VALUE- CHA
In addl
has occurred.
change . one AdJ·ustmentE vent Constructor:
J{ere 1s • . . .
int data)
AdjustrnentEvent (AdJustable src, i_nt id, mt type,
this event.
Here, src is a reference to the obJect that generated
id equals ADJUSTMENT_ VALUE_CHANGED.
type is used to specify the type of event.
data represents its associated data.
Adjustment Event class has these methods :
Description General form
Method
S.No. . Adjustable getAdjustable( )
It returns the object that generated the event
getAdjustable( )
I I. int getAdjustment Type( )
It obtained the type of the adjustment.
2. getAdjustmentType( )
int getValue( )
L It obtained the amount of the adjustment.
I 3. getValued( )

(4) The ComponentEvent class: visible/


ponent is moved, resized, hidden or becomes
A ComponentEvent is generated when a com
imisible. that can
nt events. This class defined integer constants
ComponentEvent class has 4 types of compone
be used to identify the events. The events are:
Description
S.No. Constant
The component was hidden.
1. COMPONENT HIDDEN
The component was moved.
2. COMPONENT MOVED
The component was resized.
3. COMPONENT RESIZED
The component became visible.
4. COMPONENT SHOWN

ComponentEvent has the following constructor ·


---= -D.: .:..e s_m -:-_ ip-: -:-:t io:= n:--
___ 1
~t-- -~C ons tn,c tor~ ~~- ----l ----- :-::-
~~ mp one nt Event (Component src int
type) Generated the component event.
d th. t
liere, sri . to the object that generate 1s even ·
r IS a reference
~ type specifies the type of the event.
DentEvent is the 1..- 1.... either directly or indirectly of:
•Cont..:- Uf" '&,. ._
-uierEvent
·~
- ~ent
'
A Functional Approach to JAVA OOP Found _
338 ations ·

Method of the Component Event class is :

S.No. Method Description Ge


1. getComponent( ) It returns the component that generated the event_ component

(5) The ContainerEvent Class


A ContainerEvent is generated when a component is added to or removed from a container_
ContainerEvent class has 2 types of inter constants:
l_ COMPONENT_ADDED
2. COMPONENT_REMOVED
These two integer constants can be used to identify events.
Container Event is a subclass of ComponentEvent and it has one constructor :

S.No. Constructor Description


L ContainerEvent (component src, int type It generate the container event with specified type
Component comp) and the component.

Here, src is a reference to the container that generated this event.


type specifies the type of the event.
comp is the component that has been added to or removed from the container.
ContainerEvent class has the following methods:

S.No. Method Description General form


1. getContainer( ) It obtains a reference to the container that generated container_get container( )
this event.
2. getchild( ) It returns a reference to the component that was component getchild( )
added to or removed from the container.

(6) The Focus Event Class


A FocusEvent is generated when a component gains or loses
keyboard focus_
FocusEvent class has the following integer constants that
can be used to identify these events : The third construdor and the

1. FOCUS_GAINED getOppositComponent( ) method wos added


by Jovo2, version 1.4.
2. FOCUS_LOST
FocusEvent is a subclass of Component event class and it has the following constructors :
S.No. Construdor Description
1. FocusEvent ( component src. int type) It generate the focus event with specified type.
2. FocusEvent ( component src. int type boolean b) The argwnent b is set to true if the focus event is
temporary, otherwise, it set to false.
3. FocusEvent (component src. int type, boolean b, The other component involved in the focus change,
component other) called the opposite component, is passed in other.

Focus Event class has the following methods :


n...,,.......fion
.,,==----:--::::callinS
------+------_:..,_.:::::~
1. We can determine the other comp0nent by
this method_
• rat}'·
2. It indicates true if the focus change 1s temp<>
319

A,-.:pw_,,,--.,-,__.
For__,,.,~,,,., ..
,,.-;,.,o,crollbar;._..,_

utEvent Class
(7 )'lbe InPt class JnputEvent 1s a sub class of ComponentEvent and is the superclass for component
'Jhe abstrac
Its subclasses are :
,..,ents.
jJ1pUt .,.
J. J(eyfvent
2. MouseEvent
lass defines a number of integer constants that represent modifiers. Originally, the
C
ven t defined
1nputEclass the followmg 8 values to represent the modifiers:
Jnput£vent
1.ALT_MASK
2_ALT_GRAPH_MASK
3. 5UifON 1 MASK
4. alJTI'ON2 MASK
s. BUTI'ON3 MASK
6. CJ'RL_MASK
Do You
Know?
8 modifier values :
340 A Punclion al Approac h l )
o AVA OQp F
lnput Event class has the following method s : Oundat·
IOI)\

S. No. Met1iod Descrip tion


1. getMod ifiers( ) It is used to obtain a value that contain s all of the
original modifie r flags.
2. getMod ifiersEx ( ) It is used to obtain the extende d modifie rs.

(8) The ItemEvent Class


An ItemEv ent is genera ted when a checka ble menu item (check box or
list .
deselec ted or clicked. ztern etc) .
· is selected
ltemEv ent class has 2 types of item events, which are identif ied by the followi 0
n . r
g mteger con t
S.No. Consta nt s ants:
Description

-----
1. SELECT ED The user selected an item.
2. DESEL ECTED

ltemEv ent class has the followmg constru ctor :


The user deselec ted an item.
---- ---
S.No. Constructor Description
1. ItemEv ent (Item Selectab le is, int type,
It generat e an item event with specified type.
object entry, int state) The current state of the item is in state.
Here, src is a reference to the compo nent that genera ted this event.
type specifies the type of the event.
entry specifies the specific item that genera ted the item event.
state specifies the curren t state of that item.
ItemEv ent class has the following method s :
S.No. Method Descrip tion General form
1. getltem () It obtains a referenc e to the item that generat ed an Object.getltem()
event.
2. getitem Selectab le( ) It obtain a referenc e to the Item selectab le object ItemSelectable
that generat ed an event.
3. getstate change( ) It returns the state change.
getitemselectable( )
int getstatechange( )
-
(9) The KeyEvent Class
A KeyEv ent is genera ted when any input is receive d from the keyboa rd.
KeyEvent class has 3 types of keyevents that are identif ied by these integer

S.No.
1. KEY _PRESS ED
Constants
constants
Description
These two event are generat ed when any key is
~
:

· presse 0
--
2. KEY RELEASED released . I
3. KEY TYPED This event occurs only when a characte r is generated,

VK_EN TER
VK_ES CAPE
VK_CA NCEL
VK_UP
VK_D OWN
VK LEFI'
6 _ Event Classes 341
Chapter 1

yI(_IHGHT
yJ(_PAGE_DOWN
yJ(_PAGE_ UP
yJ(_SJ-IIFT The VK constants specify virtual key cods and
these ore independent of any modifiers such
vr<_ALT as ctr/, shift or alt.
yJ(_CONTROL
t is a subclass of InputEvent.
I(eyEve n
...,any constructor s two of then are :
It has,..
~- Constructor Description
,-- .
KeyEvent (Component src, mt type, long It generate the key event with the specified type.
J. when, int modifiers, int code) The system time at which the key was pressed is passed
in when.
v - KeyEvent (Component src, int type, long Code is the virtual code such as VK_ UP. ch contains the
2. character equivalent.
when, int modifiers, int code, char ch.
L.--
The KeyEvent class defines various methods. The most commonly used Methods are :

--
~
S.No.
l.
Method
getkeychar( )
Description
It returns the character that was entered.
General form
char getkeychar( )

getkeycode( ) It returns the key code. int getkeycode( )


2.

If there is no valid character available, then getkey char() returns CHAR_UNDEFINED.


When KEYTYPED event occurs, getkeycode() returns VK_UNDEFINED.

(IO) The MouseEvent Class


A MouseEvent is generated when the mouse button is clicked, released, moved, dragged or when the
mouse actions occurred (enters or exits) in a component .
MouseEvent class has 8 types of mouse events. The following integer constants can be used to identify
them.
S.No. Constants Description

1. MOUSE CLICKED The user clicked the mouse.


2. MOUSE PRESSED The mouse was pressed.
3. MOUSE ENTERED The mouse entered a component.
4. MOUSE RELEASED The mouse was released.

~
5. MOUSE MOVED The mouse moved.

~
6. MOUSE DRAGGED The user dragged the mouse.

- 7. MOUSE WHEEL The mouse wheel was moved.

~ n
- 8. MOUSE EXISTED The mouse exited from a component.
Mo11se£ve t.rs a subclass of InputEvent . Here is one of its constructor s.

~ ; e n t (Componen t src, int type, long when, int modifiers, int x, int y, int clicks, boolean

Jlere, S1i •
c 15 a reference to the componen t that generated the event.
type specifies the type of the event.
34 2
A Fun ctio nal App roac h to JAVA Oop
F
whe n specifies the syst em tim e at whi ch oun.dati0
the mo use eve nt occ urre d. ns
modifiers arg um ent indi cate s whi ch mod
ifie rs wer e pre ssed whe n a m
x, y are the coo rdin ates of the mou se. ouse eve
nt Occ11.....
clicks specifies the click cou nt. ""(t~

triggerspopup Oag indi cate s if this t'\·ent


cau ses a pop up men u to app ear
, fl!II•"'••
1 1
.. f
_
on this pl
-~
',·h
, it•f-t,'I' '
1 ,

-•~ it•t? atforrn.

I ~;.

Java 2 vers, on 1.4 odds a seco


nd cons truct or The (1 IBut lon( ) m thod ,s odd db
which a/so allow s the bvffo n lhat caus
ed lhe vam on 1 4 Y lova 2
even t fo be spec ified

Moust!Evcnl class ddi ncs tlw ({l1lnw11


1g met hod s:
S.N o. Mct l,otl
1. gctX ( )
1Jc.scri11tir111 h~~ ~
It retu rn, lhl' X u10H li11a tc" of the
mouc;c \vhc n the t nt gctX ()
l'\Cn t ocu1 1 red.
2. gctY () 11 ,ctu rns thl' Y u1md111,1lcs ol the 111<>ll c whe n the
-~ I nt -- -- J
c, l'nt OLCllrrcd . gctY ( )
I
3. gctP oint () ll obta in the l.Oo rdm att:s of the lll•lll
~
'>t:
4. Poin t gctP oint ( )
gctC hck Cou nt( ) ll oht:1111s thl: num bn ot nwu ~e dick
s for this even t I nt getcl1ckcount( )
5. ispo pup Tng gcr( ) II tc~t., if th1-. l:\'ent c.1u,e-. a pop up
on this plat form
men u to app ear -- -- -
boo lean 1sPopup l'rtgger( )
6. tran slat cPo int( ) It change!> the lui:ation of the even t.
void tran slate Point (mt x, int y)
7. getB utto n( ) It retu rns a v.iluc that rcpr .:sen h the
butt on that mt getB utto n( )
caus ed the even t. \

(11 ) The Mo use Wh eelE ven tCl ass


-
A Mo use Wh eelE ven t is gen erat ed
whe n the mou se whe el b muv cd. A..,
has a whe el betw een left and righ t but we all kno w, generally mouse
ton and these wheels are use d for scro
Mo use Wh eelE ven t class is a subclass llin g.
of Moust:Event an<l was add ed by Java
2, version 1.4.
Mo use Wh eelE ven t has ther e two inte
ger con stan ts :
s.N o. Om lton ls
Des crip tion
1. WHEEL_BLOCK SCROLL It gene rate a pag e up or pag e dow n
scro ll e\·cnt.
2. WH EEL _UN IT SCROLL It gen erat e a line up or line dow n :.cro
ll event.
MouseWheelEvent defines the followi
ng con stru ctor .
Mo use Wh eelE ven t (Co mp one nt src,
int type, long when, int modifiers, int . . I' ks boo1ean
trig ger s Popup. int scrollhow. int amo x, mt Y• mt c" '
unt , int count)
Her e, src is a refe renc e to the obje
ct that gen erat ed the eve nt.
type specifies the type of the eve nt.
when specifies the system tim e at whi ch the
mou se eve nt occ urre d.
,nodifiers argument indi cate s whi ch mod ifie rred-
rs wer e pres sed whe n a mou se eve nt occu
x. y are the coo rdin ates of the mou se.
didcs spe a6e s the click cou nt.
Fn'lll c1 •• ~~,.,~ 343
th,11*•1 I<>
, . Pomip flag indicales if. this event causes a pop up menu to appear on this platform.
(fll;,.~tr~t
,c;v//holl' specifies Lhe value either WHEEL_ UNIT_SCROLL or WHEEL_BLOCK_SCROLL.
• 1 specifies
the number of units to scroll.
111110Ul1
•ndicates the number of rotational units that the wheel moved.
corm t 1
, eelEvent defines the following methods that give access to the wheel event.
,touse\\ h
' },fetliod Description General form

) ,·o. , Whee!Rotation() It returns the number of rotational units. int getWheel Rotation( )
1 ' get The positive value indicates the wheel moved
counter clockwise and negative value indicates the
wheel moved clockwise.

It returns the type of scroll i.e., either WHEEL_ int getScrollType( )


UNIT_SCROLL or WHEEL_BLOCK_SCROLL
If the scroll type is WHEEL_UNIT_SCROLL, we int getScrollAmount()
can obtain the number of units to scroll by this
method.

(IZ) 1be TextEvent Class


ATextEvent is generated when the value of text field or text.
. tered or changed. Instances of TextEvent class describes
:\rea 1s en
-1tma,
The TextEvent object does not include the
11rt el'ents. characters currently in the text component
Text Events defines the following integer constant : that generated the event. II differs from other
event objects. For this reason, no methods are
:EXT_VALUE_ CHANGED
discussed here for the Tex/Event class.
One Constructor ofTextEvent class is:
':'extEvent (Object src, int type)

Here, src is a reference to the object that generated the event.


type specifies the type of the event.

(13) The WindowEvent Class


ed,
A WindowEvent is generated when a window is opened, activated, iconified, closed, deactivat
/.econiJied or quit. Toe object of this class represents the change in state of a window.
W'mdowEvent class has IO types of window evnts. It defines the following integer constants to identify
~

Constants Description
DOW_OPENED The window was opened.
DOW_ACTNATED The window was activated.
DOW_ICONIFIED The window was iconified.
DOW_CLOSED The window has been closed.
OW_CLOSING The user requested that the window be closed.
W_DEACTIVATED The window was deactivated.
W DEICONIFIED The window was deiconified.
_GAINED FOCUS The window gained input focus.
_LOST FOCUS The window lost input focus.
STATE_CHANGED The state of the window changed
s•• ,\ I 1111, li1111,il 1\pprnt1 r h to Ji\V
,\ Ocw I
1
\\ rndtm I , -rn\ 1:-. i\ ,;u\h lus~ 1,.l( l \ 111lplH 1cnl Event. 1t d('f111c s I he following
' hr1d
ti 1
c;on<:t ruct
:S.1'\b hrs
Cm,st rfldor ·
l \\ m,t,m h , nt l\\findl ,,,. 1'1<, int typt')
\\ md1..1,, r, 1..'nt l \\"mdo w src, int type, windo w other)
\\ mdowE vcnt (\Vind ow src, int types, int from state, int to state)
-0. \\'indo wEven t (\Vind ow src, int types, windo w other, int transla
te, int to state)
Here. src is a refere nce to the object that genera ted this event.
type specif ies the type of the event.
other specifies the oppos ite windo w when a focus event occurs .
froms tate specifies the prior state of the windo w.
tostate specif es the new state that the windo w will have when a Windo
w t
sate chang
' ' ' ~ -...• •
e occur1.
I - --"'W""'l•

Origina lly, Java has the first construc tor and method . Other 3 construc
tors and methods
are added by Java2 version 1.4.

Windo wEve nt class has the follow ing metho ds :


S.No. Metho d Descri ption Genera l form
1. getWi ndow( ) It returns the windo w object that genera ted Windo w getWindow()
the event.
2. getOpp ositeW indow () It returns the opposi te window , the Windo w getOppositeWindowt)
previo us windo w state and the curren t
windo w state.
3. getOld State( ) It gets the old state of the window . int getOldState( )
4. getNew State( ) It gets the new state of the window . int getNewState( )
.... \ ,
,

• IIIOlf commonly used method in Window Event class is get Window


( ) method.

1.6.3 EVENT LISTEN~~~


r.ni
. dm
As we have stud 1e · previo
· us · n, A · some t· 1
sectio n event 1s ac 10n (or t ng
· ger) 1·n 1·ava that vourpn.g
. • 'lhi~ h,Ul,Ut'r 11
h.u to listenfor. To handl e an event, develo pers need to imple ment an event
hstener.
contain the method(s) that should be imple mente d.
h )d Je ~
In short. we can say, when an event occurs , the event source invoke h ) wi,\te met l
s t e appn. l
by the listen n and provides an event object as its argum ent.

16 3.1 Event Ustener Interf ace


. tert;ict' "h'
v nt Listener repres ent the interfa ces respon sible to handle events. It is u ,narke r 111
. ·
every listener interface hu to extend . p1
.
e tl.H:k,1ge' 1
LiatMr Interface las i define d m Java.u til pal;kagc .md the 1astene .111 tcrfoce s ,1r r
r
awt~ nt •
345
_ Event Classes .
16
~ chapter
to be unple ment ed for hand ling diffe rent
. terfac e has one or more meth ods that need
Jjstener 1.11
e~cf events
b
.
ds 0 ·
ion
l:iJl ctass D~~-rarat
.. ........... .
va.util.EventListener inter face is:
463,? ... ..... ,...... . for;·a
" . .... declaratwn ..
~e publ ic i n t erfa c e Even tlist ener

aces, meth ods and a brief descr iptio n:


. g table has a list of comm only used listen er interf -------,
~efotloWID~-- - - r - - - - - - - - - - . - - - - - - - - --
Meth ods Description
~ ustener Interface
This interf ace defines one meth od for
~
I s!1°· ActionListeners
~
action Perfo rmed ()
receiving the action events.
I 1. -
ad1us tmcnt Valuc Chan ged() Thh interf ace defines one meth od for
L.--,--- ---Ad"ustmentListener receiving adjus tment events.
2. J

Comp oncnt l1idd <'n() Jt defines 4 meth ods for receiving the
L-- ~pon entL istnc r comp onent event s.
J, Comp oncn tShow n()
Comp oncn t.Mow d()
Comp onent Rcsiz ed( )
- --- --+ --~ -
It define,; 2 meth ods to recog nize when a
~
Comp oncnt Addc d( )
~ -ContainerListcncr comp onent is added to or remo ved from a
4. Comp ont'n tRern ovcd( )
conta iner.
I
focuslistener
- focu~Gairwc.f ( ) It defines 2 meth ods to recog nize when a
I s. comp onent gains or loses keybo ard focus .
focu.-.1..ost( ) - --- ~-- --- ---
--- --- --1 --- ., -one -- · -
..... --- --1 --- ---
nged( ) It define_ meth od to recog nize when the
iteSta lcCha
6. /I Item rstener
L"
...tatc of an item chang es.

keyPr essed ( ) It defines 3 meth ods for receiv ing the key
KeyListener
I

7,
keyReJeased{ ) event s.
i keyT yped ()
mous ePres sed() It defin es 5 meth ods for receiv ing the mous e
8. MouseListener
mous eClic ked( ) events.
I mous eEnte red()
mous eExit ed()
mous eReJe ased( )
9 mous eDra gged () It defin es 2 meth ods for receiv ing the
· MouseMotionListener
_ _ _---l
-rn-o_u_s_eM_o_t1_·0_n_E_v_e_n_ts_ _ _ _ _ _
--i--------_J__m:_o_u_s:._e_M_o_v:_e_d...:(:..::)~----~
mous eWhe elMo ved() It de.fines one meth od for receiv ing the mous e
IO. M<>useWbeeJListener
whee l events.
r--- _ _
1
-+1-I-td_e_fi_n_e_s_o_n_e_m_e-th_o_d-to_r_e_c_og_n_i_ze_w_h_e_n_a_-1
tCh_an_g_e_d_(_)_ _ _ _
__
It 11-:-entist-:-._en_e_r_ _ _ _+-te_x

......._ r---.. . -i-----=-----------1


I
text value chang es.
12. W - l l l d • - - - - : - - - ~ - 1 -
-------
0 It defin es two meth ods for receiv ing the
wind owGa ined. Focu s( )
wFocusListener
~----- wind owLo stFoc us( )
-:-:----+-~.:....:..:...::..:..=...:..::.......:....:.:...__:_:___ _+---- - -s.- - - - - - - - t
wind ow focus event
\Vi
It defin es seven meth ods for recei ving
IJ
indowlistener wind owO pene d( )
wind owCl osed( ) wind ow event s.
wind owCl osing ( )
wind owA ctiva ted()
wind owD eacti vated ()
wind owko nifie d()
wind owDe iconi fied( )
346 A h1m.l 1onal Apprnach lo JAVA O< , ,
)I h,un I-
l. 'lhc Adio nLis tenc r Interface: < ,11,,,11,.

'I he Al t1<m Liste ner Inter face defin e the actio nPer
form ed() meth od whic h called wh
(hXll rS
'. en an act·
Gene ral form of this meth od: Jc,n
t-r
void actio nPer form ed(A ction Even t ac)
2. The Adju stme ntLi stene r Interface:
The Adju stme ntLis lener Inter face defin es the adju
stme nt valu eCha nged () meth od h·
an adju stme nt even t occu rs. W tch I
ca led "-'hen
Gene ral form of this meth od:
\1
void adju stme ntVa lueC hang ed ,,.
(Adj ustm entE vent ac)
3. The Com pone ntLi sten er Interface:
The Com pone ntLi stene r Inter face defin e four meth The compo nentM oved and
ods as compon
given in prev ious table whic h are calle d when metho d are provid ed for n f'f/ .enfResiied()
a com pone nt is only.
0 1
co lion purpo
hidd en, show n, mov ed or resiz ed. les

S.No. Meth od Gene ral Form -


1. ComponentHidden( ) void comp onen tHidd en (ComponentEvent ce) -
2. ComponentShown( ) void componentShown (ComponentEvent ce)
3. ComponentMoved( ) void componentMoved (ComponentEvent ce)
4. ComponentResized( ) void componentResized (ComponentEvent ce)
4. The Cont aine rLis tene r Interface:
The cont ainer Liste ner inter face defin es two meth
ods to reco gniz e when a comp onen t is added toor
remo ved from a conta iner.
(i) Com pone ntAd ded( ) meth od : Whe n a com
pone nt is adde d to a cont ainer is called
com pone ntAd ded( ) meth od.
(ii) Com pone ntRe mov ed( ) meth od : Whe n a
com pone nt is remo ved from a container is called
com pone ntRe mov ed( ) meth od.

S.No. Meth od Gene ral Form


1. ComponentAdded( ) void comp onen tAdd ed (ComponentEvent ce)
2. ComponentRemoved( ) void componentRemoved (ComponentEvent ce)
5. The Focu sList ener Interface:
The Focu sList ener Inter face defin es two meth
ods to reco gniz e when a comp onen t gai·ns or lo,c)
keyb oard focus .
(i) Focu sGai ned( ) meth od is calle d when a com
pone nt obta ins keyb oard focus au<l
(ii) Focu sLos t() meth od is calle d when a com
pone nt loses keyb oard focus.
SNo . Meth od Gene ral Form
1. Focus(~ained( ) void focusGained (FocusEvenl fe)
2. Focu sLosl ( ) void focusl.ost (focu sEve nt fe)
6. The Item Liste ner Interface: . ·1hc
. 11 changes,
The ltem Liste ner inter face defin es one meth od
to recog nize when the stale of an ite1
item state chan ged meth od is calle d when there
is any chan ge in the state of item.
347
_ h l'lll <'J,1sst•~
t 'h,1J'l<'r 1t,

...,._..... lf this n1cthod is:


, ·ti (tll'll l t
l
'
d ( I te mEv e n t 1 e)
(1l
'•Jtl l' 'd •rem:, tat ~ c rn ng t:!
1•0 l l

., ,1jstencr Interface:- . .
,., 'lhC Kt} , •
cr intc
-
rfJc e defines thre e met hod s for rece1vmg the key events :
,. •. ,
. t,.:t'rl.t!i 1t 11 hod
.
ts called when a key is pressed·,
·
lhl ·) '( ll' t, k,,,f Jresscd () met
1 released and
(
1
Rt•le·ised( ) method is called when a key is
·· ) kl'V
n a character has been entered.

('.'. k, '·T)rped( ) method is called whe
(ill) t:)
. three events are
f1r
1
l•xmnple :
release an}' cha ract er key 1.e. A or I or$ etc., then all of these
(') If we press and
d and released.
crenerated in sequence key pressed, type
1
FS etc. then only
s and rele ase any fun ctio n or related key i.e. Page Up or Home or
·') ~- we pres s of these
are gen erat ed in seq uen ce - key pressed and released. General form
(ll two key !!Wills
methods arc:
Met/rod General Form
S.No. ---
- - .

I. keyPressed( ) ~ kcyPressed (KeyEvent ke)


·--
2. kcrR eka sed () void kcyRelcased (KcyEvent ke)
-~ ----- ·---
3. keyTyped() void keyTyped (KeyEvent ke)
--

useListener Interface:
8, Jhe Mo
hods for receiving the mouse events:
The .i\IouseListener interface defines 5 met released at the
seC1ick ed( ) met hod is called when the mouse button is pressed and
(i) The mou
same point. ent.
ed when the mouse enters a compon
(ii) The mouseEntered( ) met hod is call
(ill) The mouseExited( ) met hod is
called ,vhen it leaves.
n the mo use button is
eleased( ) methods are called whe
(iv) The mousePressed( ) and mouseR
p~ d and released, respectively.
General forms of these methods are :
Method General Form
£No.
1. mouseClicked( ) void mouseClicked (MouseEvent me)

2. mouseEntered( ) void mouseEntered (MouseEvent me)

3. mouseExited() void mouseExited (MouseEvent me)

4. mousePressed( ) void mousePressed (MouseEvent me)

s. mouseReleased( ) void mouseReleased (MouseEvent me)

9
•Dae MouseMotionListener Interfac
e:
events.
ionListener interface defines two methods for receiving the mouse motion
1he MOUSeMot
--~,;.~. Description
.... ~ ' ~ .':.:_ -
- General fon n
is
It is called multiple times as the mouse
IIIOasel>ragged( ) void mouseDragged (MouseEvent me)
dragged.
'-. . is
It is called multiple times as the mouse
~() void mouseMoved (Mouse Event me) moved.
.............

It 'Ille Mo.se . .
\e ~ Wh ~is ten er Interface:nes one method for rece1vmg the mouse wheel event.
Wheelustener interface defi
348 A Fun ctio nal App roac h to JAVA OO
P Fo d .
un ations
Thi s me tho d is call ed wh en the mo
use whe el is mo ved .
- - - --------,---
---------: G-:-e_n_e_r_a-;lF=-o-rm
_ _ _ __
S.No. Met hod
1. mouseWheelMoved() void mouseWheelMoved (MouseWh
eel Event mwe)
11. The Tex tLi sten er Interface:
The Tex tLis tene r inte rfac e def ines
one me tho d to rec ogn ize wh en a
Tex tCh ang ed( ) is call ed wh en a cha tex t val ue changes.
nge occ urs in a tex t are a or tex t fiel
d.
S.No. Met hod Gen era l Form
1. textchanged( )

12. The win dow Foc us Lis ten er Inte


The win dow Foc us list ene r def ines
void textchanged (TextEvent te)

rface:
----
two me tho ds for rece ivin g win dow
(i) The win dow Gai ned Foc us( ) me foc us eve nts.
tho d is call ed wh en a win dow obt
(ii) The win dow Los tFo cus () me ain s inp ut focus.
tho d is call ed wh en a win dow loss
es inp ut focus.
S.No. Met hod
Gen era l Form -
1. windowGainedFocus( ) void windowGainedFocus (Window
Event we)
2. windowLostFocus( ) void windowLostFocus (WindowEvent
we)
13. The win dow Lis ten er Interfac
e:
The win dow Lis ten er inte rfac es def
ines sev en me tho ds for rec eiv ing
(i) The win dow Op ene d( ) or win win dow events:
dow Clo sed ( ) me tho ds
are call ed, respectively, wh en a win
dow is ope ned or
clos ed.
(ii) The win dow Clo sing ( )
me tho d is call ed wh en a win -
dow is bei ng clos ed.
Mou se Whe e/Lis tene r interlace and
(iii) The win dow Act iva ted (
) and win dow Dea ctiv ate( ) Win dow focu s Listener interface was
me tho ds are call ed wh en a win dow added by
is acti vat ed or Java 2, version 1.4.
dea ctiv ated , respectively.
(iv) The win dow lco nifi ed
and win dow Dei con ifie d me tho ds
or deic oni fied , respectively. are call ed wh en a win dow is iconified

S.No. Met hod


Gen eral Form
1. windowActivated()
void window Activated (WindowEvent
2. we)
windowClosed( )
void windowClosed (WindowEvent
3. we)
windowClosing( )
void windowClosing (WindowEvent
4. we)
windowOpened( )
void win dow Ope ned (WindowEvent
5. we)
windowDeactivated( )
void windowDeactivated (WindowEv
6. ent we)
win dow kon ifie d()
void windowlconified (WindowEvent
7. we)
windowDeiconified( )
void windowDeiconified (WindowEv
ent we)
Ho w to cre ate an Eve nt Lis ten er
in Java?
Let's see how to cre ate an eve nt list
ene r in Java. Fol low the se thre e step
Ste p 1 : Cre ate a clas s to imp lem ent s for the sam e:
a giv en list ene r inte rfac e.
pub lic cla ss abc Eve ntH and
ler imp lem ent s
abc Lis ten er
and Listener ~n ter fa~
ses and listener
acbge provides the following event clu

, •• w

Object
AdjuatmentLJstner The.Ad
AdJ
ComponentLlatener

CcJatltaerLlltener
350
.,...
A Fum.tlonal Approach to JAVA OOP Found t ........
~
pLogtam p = new program (f);

class program impliments ActionListener

static int count=0;


Buttoon b;
Textfield t;
program (Frame f)

f. setSize (200, 200);


f.setLayout (new flowLayout( ) ) ;
b = newButton ("OK")
b.addActionListener(this);
t = new Textfield("H_imanshu Garg", 30);
f.add(t);
f. add (b);
f.setVisible(true);

public void actionPerfomed (ActionEvent e)


{

if (e.getsource( ) ==b)

count++;
system.out.println ("Button is Pressed");
t.setText("Himanshu Garg"+ Count);

Command Prompt - Java MyFrame 19 g El

H:\Core Java\Chapter > javac MyFrame.java


H:\Core Java\Chapter > javac MyFrame

Himanshu Garg Hlmanshu Garg Click 1

You might also like