0 ratings0% found this document useful (0 votes) 396 views64 pagesObject-Oriented Programming With Java 7541-880
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Inheritance and
Polymorphism
“a IL. this chapter, we will deseribe to important and pow
fl featres in object-
‘nent programming—snhertane and polymorphism, The inentance fears of
objectoriented programming wa intediced in Chace We wil provide a mote
w= TO
aiste aceite + test +t) 80
‘What kind of objects should we use to model undergraduate and graduate
studeots? There are basically two broad Ways o design the classes to mode! them
The firs way isto define (wo unseated clases, one for undergraduate tudeats
and another for graduate stagete, We call the wo classes slat claves they
fe not connected in an ineriance relationship, tat is if ether one isan ancestor
or descendant class ofthe other and they donot share a common ancestor' The
Second way is to model undergraduate and graduate students by wsing classes that
se relted in an inhertance hierarchy
Defining two unrelated clases for eles that share common data or behav-
Jor would ake clas definition ineffective because we would end up duplesting
code common to both classes Aldiough diferent, graduate and undergraduate
students do share many common data and behavior, 50 we wil design these 0
classes by using inheritance
‘We vil actually define three classes, The isis the Sten class to incor
porate behavior and data common to both graduate and undergraduate students. The
Second and third clases are the GradusteStudent clas 10 incorporate behavior
Specific to graduate students and the UndergradusteStudent clas to incorporate
[behavior specie to undergraduate students. The Student elas is defined as
felass stodent
public seudest () (
hte cnke Kae)
"ec wnng sume
,
public string geteoursegrade( )
,poblic int gecrestseore(ine tezttanbes) (
‘return seo" [vesthasbes“1]
public void sethane (String newline) {
public vous aecrestseore ant cestifanber, nt testseore) (
sez (rectiunger i] vestscores
public void conputecoureezade( ) (
[Notive thatthe modifier forthe instance variables is protected, making them
visible and accessibe fom the instance methods of te class andthe descendant
Clases. I you declare a data member of clase private he this dala member i ae
eeible from the method ofthe class only. I You declare a dala member public,
this data member i accesible from everywhere, We declare them protected to they
se accessible from both the methods ofthe cats and the descendant classes. We
‘ill explore fuer the protected modifier later in he chap
‘We deine the classes UndergraduateStudent and Graduatestudent as sub
classes of the Student clas. In Java, we say 2 subelass events soperclas. The
thfference bowen the clases GraduateStudert and UndergradusteStuden esi
the way their inal curse grades are computed, The two subclasses are defined as
fellows
student extends student ¢
public void conputecourseccase() (
for (ine = 0) 1 nM
totale eese (ile
,
dalse t .
,
public vosd cone
ecouzsetzade() (
for (int i= tr 1 © ALOR TESTS; £1) (
otal t tests
,
Af (cotal/mmLor_snets >= 18) ¢
y alse ¢
>
Figure 13.1 shows the class dtgram relating the thes classes. Notice the we
ofthe pound symbol forthe protected modifier Notice also that we do nat show
Inerited data members and methods inthe subclasses. By seeing an inheritance
arow connecting asubelass ois superclas, we know that datamembers and meth
‘26s indicated on the superclass ae applicable to the subclases also. We atach
rethods and dala members (othe sbelasses only if they are deine inthe sub-
Classes or they are overridden inthe subeastes, In Figure 13.1, both subelases
Ihave the method computeCourieGrade tached hem beeause the method is over
ridden inthe subelases,
+ NNO TESTS
7 Sede ve
4 Sine) wie
+ encom) Ste
4 Sesame) See
4 frneeeac it
{eerie ned
4 Simpl) Sting
c- 4,
Tepes Galatia
+ campoeComGrede) Sting + apc) Sing
Figure 13.1. A superclass Student and is sbdsesGraduateStudent snd UndergraduateStudentyethrmerton 781
1, Which isthe sobelae and
isthe soperclas inthis declaration?
2. Which visibility moder allows he data members af a superclass to be
secenbl tothe intances of belies?
13.3 | Using Classes Effectively with Polymorphism
[Now let's ste how the Student class and is subclases can be wed effectively in
the clay rover program. Since both undergraduate and graduate students ate ex
rolled in a elas, should we declare the two atays shown below to manta the
class roster?
Ondergredsatestedest indergradRoster [20];
We mentioned in Chapter 10 that an array must contain elements ofthe same data
type, For example, we cannot store integers and real numbers inthe same array. To
fellow this rule, it seems necesary for us to declare two separate arrays one for
graduate students and anotee for undergraduate studevt. This ul, however, does
‘ot apply when the array elements ate objects. We only nee to declae single
tara. fr example
Student ester (4007
Elements ofthe roster aray can be instances of sither the Stent class or any ofits
{descendant GraduateStudent of UndergradusteStudent clases. Figure 132 ili
‘wales the aay with both (pes of students av atay elements.
‘efore showing how this array is ured in the program, we will explain
the concept of polymorphism. Int simplest form, polymorphism allows a single
Figure 13.2 Theroser aay wh element refering we nstance of
Undergraduatestudent cdsse:
Panton
variable to refer to objets from difeent classes. Consider, for example, the
declaration
With this declaration, we can say nt only
student = new studens( 14
butato
student = new ceadusrestudent( )
student = new Undergeaduatestugent (9
In other words, the single variable student isnot limited to refering to an
‘object fom the Student cats but caffe o any object fom the descendant lasses
fof Student Ina similar mannes we can ry comeing lke
roster{o] ~ new Geaduatestudent (7
Fovter(1] = new Jedesqzeduatescudent ( }2
Foster[2] ~ new Dngergreduatestogen (1)
Foater[o] = new Graduatestudent ( )
However you caiot make a variable of class X refer to an abject from the
Sng hues suporlacs or sibling classes of X. Sling vlnves age thore that share the cone
son ancestor class. For example the following assignment statements ae both
‘vali
eset = new Student (1s
X worwaun —e| Seag2 = new Undergesduacescudect ( )
Now to compute the course g.
ude using the roster array, we execute
for (int i = 07 1 < nunerofsudentes G4) (
foeter{u] conputeco.oesvade ()s
>
1 roster refers to a GraduateStudent, then the computeCoureGrade method of
the GraduateStudent clases exovuted; an if it refers to an UndergradusteStudert.
then the computeCourseGrade mod of Undergraduatestudent is executed
‘We cll he message computeCourseGrade polymorphic because the message les
to methods from diferent classes depending on the object referenced by roster
Polymorphisme allows us to maintain the eats roster with one array instead ofbene
ehrershom
yu rymepton 78
rainaining separate anay for each type of student, and ths simplifies the peo
cessing wemendously
"Notice tht the statement
nthe sample code works because we defined the computeCourseGrade method in
the Student clas. Tae metod does nothing Gs method bodys empty), sits pur
pose may not be abvios, But without this method i the stadent clas, the ste
‘ment would teat in an efor We explained the reason atthe end of Secuon 131. 1f
the computeCourseGrade method were not defined inthe Student class, thea the
method sould be unaque to the individaal subelases, requiring ws to wypecst
the expression roster fo iter Undergraduatetudent or raduatetudent. Such
lypecasting, ofcourse, canels out the Benes of polymorphism, Instead of det
ing the computeCoureGrade method in the Student class with an emply body, we
‘could define tas an abstract method, We wll define an abstract method and explore
ts uses in Section 13.6,
‘Polymorphisms makes possible stooth and easy extension and modification
of a program. Suppose, for example, we have to add third type of studeal, sy,
Sod stodent, (othe class roster program. I! we have to define separnte sry
for each tye of student. ths exteason forces us to deine a new cass and a third
array for audit suadents But with polymorphism, we only have to deine a new
Subclass of Student. And as long as this new subclass inches the correct com-
putecourseGrade method, the for loop to compute the couse grade for tudents
Femins the same. Without polymorphism, not only do we have to add the new
Code, bat also we have to rewmte existing code to accommodate the change.
‘With polymorphism, onthe other hend, we dont have to toach te existing code
Modifying existing code isa tedious and exorprone activity. slight change (0
sting code coud ease a program to stop working comets. To be certain that
{ange in one portion of exstng eode won't lfect ober portions of exsing code
Suversely, we must understand the existing code completely. And understanding
Cae, especially one thats long andor waten by somebody cls, i avery tne
consuming ask
‘Aa element of the roster aay is a reference to ap instance of either the
GraduateStudent or the Undergraduatestudent class. Most of the time, we do not
have to know which ie which There ae times, however, when We ned fo know the
clase ofa referenced objet, For example, we may want to find othe nimberof|
Undergraduate students who pasted the course, To determine the clas of an objec,
‘ve use the instanceof operator. We use this operator a follows
Student = new Urdergesdustestudest ( )
A (x snstanceot Uscecgeaduatestudeat } (
System cou sprintin(tue. Xie an undergraduate otadens"?
yaite t
Systen.out .printin(Me, X Ls a graduate student"),
,
Panton
“This will printout Mr. X isan undergraduate student, Te following code counts
‘he number of undergraduate students inthe reste array
for int to ete
af Croscerti} inatancest Crdergraduarectudent )
1. Suppote Tuck and Motoreycle are ubeasies of Vehicle, Which af these
declarations ate invalid?
suck t+ new Vehicle(yz
Vehicle yo new truckthy
Notozeyete 21 = new Vensele()
Metezeyeie a2 = new TEuek
2 Whatis the purpore ofthe instanceof operator?
13.4| inheritance and Member Accessibility
‘We will describe the rales of inheritance in his section and Sections 13S and 13.6
Tn this tection, we will explain which members (Vatables and methods) of super-
class at inerted by a subclass and how thete members ave acessed. Tn adiion|
to declaring membets private and public, we can declate them protected. The
protected modifier is meaningful when used with inhertance. Consider the fllow-
Ing declarations:
EEE ST | pertain
public int public super_rield)
poblic supert)clase Sup extends super (
pablic sub() |
,
[Notice thatthe two classes Super and Su ate placed in the separate packages, We
reed to place the Sub class in «package diferent rom the package oft superclass
to show the effect of the protected modifi. 1 both the superclass andthe subelaee
fae in the same package. the protected moier has no effect (it behaves the same
‘she public moter)
‘We use insance variables for illstrtion, but the rules we describe here ae
sequaly applicable to other pes of members (class variables, class metbots, and
instance methods), We use the graphical representation shonin Figure 13.3 forthe
tues modifiers,
‘You already know the difference between the public and private modifiers.
public member is accessible from everywhere, but a private member i accessible
sox Sor Coptic
= — Ee
S S Ses
co i
a
= = fosters
co cyl] peda pe othe
S S shcee
co co
S
S
Figure 13.3 Agraphcal representation of sperdases andes wth public private, and protected
rember Woe Te reretentation foo staton purposes on ands not 3frmal UML Sgrn)
X nora
1 worvauo
Panton
‘only within she sme class. Lets illustrate his pint. Consider a class thats ure
Tited to the clase Super and Sub
class cient ¢
public wesd teat ()
Super, ysurer = new Supers
,
Public members of «class, whether they ate inherited or not, are acessible
from any objector class. Private members of 2 cass on the other hand, are never
accessible rom any outside object or clas. The following statements, f placed in
ofthe chet class, are therfore all inva
‘A protected member can be accested from the clases in the sane package and
the subclasses in other packages. Ii not accessible fom the unclated clases in
other packages. The following statements, placed in he tert metho ofthe Cent
lacs, ae all aval
Figure 13.4 summaries the accesibiltyof cass members from a method of
anuncelated clas ina different package
‘Now let's study the eccessbiity of class members fom the methods of a Sub
‘objec. method inthe Sub object can access both the protected and public mem
bers of Super, but not the private members of Super. Figae 135 summarizes the
accessiily of members rom a method ofa Sub object.
Figure 13.5 shows the case where a method of 4 Sub object is accessing
members ofiselt Everything except the private members of the Super sass it
‘ccetsible fom a method ofthe Subclass,
‘What about accessing the members of an object from another objec that
bbelongs tthe same class? If member X, whether iberted or defined in aes, i
accesible from an netance ofthe clas, then Xie leo accesible from all instances
Of the same class. Figure 136 illustrates that an instance can access members of
‘othe instances ofthe same claspackage ene
Sue Janome
Ace trom cy xaaeeae
thechenteeted co
aa package
=
=
cigacenaaeeney PLES
Sinden re I
teste snsepege abe =
ir 13.4 The ferencebetween public private apd protected modifiers Only publ members are
‘rte Sub case
Jaane
x -toacenale
Figure 13.5 The ference between public private ae protected modiers Everything exept
private member ofthe Super dr: fom smethog of he Sub cn
| eset orgie
Figure 13.6 Oatamembersacesble om an stance ae abo accesible om oie instances ofthe
same cht.
78 chapartd stecanaandPoentin
Consider the fellowing two methods inthe Supe and Sub classes
class Super
publie void supesTosuper Super ancthersupest
J ap —> | ine + = anornersuper vrotected. super Pies)
1
>
class Sub extends Super (
public void suorosun (som anatnersuh (
¥ wa —> | ine 5 ~ anothessup.protectea seb tele:
J up —»| 28 2 7 sneshestub.public. super Fields //inherites
X NOTVALID em int n = anotnersuh. private super Feld
>
All the statements inthe two methods. except th last one in subToSub, are
vil because members accesible a objec are also accessible om other objets
ofthe same ela.
esses outside the package, s the
package visit.1 Wis pivate member ofthe Supe lass, X accesible hom a subelas of
2 Wise protected member ofthe Super elas, is X of one instance accessible
{om another instanceof Super? What sbout rom the istnoes of a abeass
of Super?
13.5 | Mheritance and Constructors
{In this section, we explain the connection betwen the constructors ofa lass and
the inhertnce mechaniem, Unlike oer members of «superclass, conerucor# of &
superclass ae not inherited by its subclasses. This means that you must define «
‘onstrctr for» class of use the deft constrctor added bythe compiler AS We
Ientioned in Chaper 4, 4 default constructor i added to a elast sf You do not
‘eclae any constrictor forthe clas. A clas definition such at
public void saylelte( ) (
Syston out psintia (el,
is equivalent to
clase Person (
public Pessont ) (
TOUS] seer —— user ales
public void cayielle( ) (
systen-out pinta (Hell, seile."s
“The statement
super
calls he superelass's constructor. Every clas bas a superclass. Ifthe class dela
Hon does not expicily designate the superclass with tbe extends clase, thea the
class's auperlat isthe Objet clas.
Panton
I you declare a constructor, then no default constructor is added tothe clas
For example, if you define a clas as
1 hyeleee ¢
public syclase(int x} (
,
then a statement such as
yelase Gest = new Mycoses
‘is invalid because MyClas has no matching constructor
the constuctor you define doesnot contain an explicit al toa superclass
constructor then the compiler add the statement
seperth:
asthe frst statement ofthe constroctor. For example, if you deine a constructor as
clase myctass ¢
public syciaze( ¢
,
‘en the compiler will write the constrictor to
pubtte myctasst) ¢
,
[Let's look at another example. Consider the flloving class definitions
class ventexe (
public Ventele(steing ventclezannbes) (public string set¥ont) (
,
Since the class has 4 constructor, oo default constructors added to the clas, Tis
means a statenent such st
veniele aycar = naw Ventele(s
cases «compilation xror because the class does nt have a matching constrictor,
This is actually what we want because we do not want to create an instance
of Vehicle without «vehicle identification number Now let's considera subelass
‘efntion for trucks. A Truck object has one additonal instance variable called
‘argoWeighitmt that ofr to a axiznun weight of earg the Wack ean ety We
sume the wuek's weight iit fr cargo can Vary (a, depending on how auch the
‘owner pays infes), Here's ou frst attempt:
public void cectesgnerande lane aevinse) (
,
we compile this definition, we will eta compiler err, Since no constuctar
is defined forthe lass, the compiler adds 2 default constructor
public void Truex) (
wert)
This constructor call the superclass constructor with no arguments, ba there's |
matching contrutor nthe superclass Thus, the compilation er cess. Here's a
‘comect definition
siete noes inenn
Srnngcvtecan y Snsennsgheni
public void cetteightLinit lint aevLinit) (
,
public int getketgnerinse th (
[Now lets apply this knowledge tothe design ofthe Undergraduatestudent
and GradusteStadent clasts, I we watt a constrictor thet accept the name, then
‘we need to define such a constructor in both classes because the conericor defined
Ir the Student clas i no inberited by these classes Notice that we ca crete
instances of thet classes by
student] = naw Onderaeadsacescodant (4
Student? ~ new cragcavestaders( Ty
ocause the default constructor is added by the compiler, not because the one de-
‘ane in the Stadent class inherited by the subelases. Remember that constructors
fof asuperlass are not inherited by its subelases.
ere are azul and a guideline o remember fora subelass constructor
S\ ttaclasshas asuperciass that not the Object lass, then include an explicit
«alto aconstructor ofthe superclass in the constructor ofthe cass.
1. Always provide a constructor for every class you define.Don'trey on default
constructors.
1. How do you el the superlas' constructor fom its bela?
2. What statement will beaded to a constructor of sabelas iit is ol ned
sn the contactor expily bythe programmes?
‘3. Modify the definition of Graduatestudent ad UndergraduateStudent in
Section 13. so we can create thei instances inthis Way
student = new Cndergraduatestudent 1
Student? = new Gndergradvatestudent (ste
Stidenea ~ naw Grasuatestudent ()
Shidencd = new Grsaustestuden (6s. tasters
peeese"hs13.6 | Abstract Superclasses and Abstract Methods
When we define a superlas, we oflen do not need o ereate any instances ofthe
superelass Ip Section 13 5, we defined ihe Student saperelas and its two subclasses
GraduateSudent and UndergraduateStudent. We gave examples of creating i
stances of GraduateSuudent and Undergraduatestudent bl notof ceating instances
of Student Does t make sense to create an instanceof the Student clacs? Depending
fon whether we ned to eeate instances of Ste, we mut define the clas der
ently We wll describe different ways of defining a sopeclss i ths section.
Eventhough we ean create an instanceof Student if we want vo (because of
the way the class is eutently defined), is there a need to create an instance of|
Student? Ifa student canbe only a graduate or an undergraduate sudeat, then there
is no need to create an instanceof Student. In fact, because ofthe way the clas is
defined, had we created an instance of Student and stored iti the reser ata. the
program would crash. Why? Because the Student clase dacs not have a compute
CourseGrade method
Inthe following discussion, we will consider two cases. In he fist ese, we
assume tha a student must be either a graduate or an undergraduate stent. Inthe
‘cond eae, we assume tha a student docs not have a be a graduate or an under
raduate student (ep, the student could be @nonmaticulatd auditing student)
Case 1:Student Must Be Undergraduate or Graduate
For the case where a student must bea graduate or an undergraduate student, we
only need instances of GraguateStadent and Undergradustestusent So we mist
dedne the Student elas in such a way tat no instances of i ean be created. One
srcihss way isto deine Stent a an abstract clase. AQ ora clovris ease dined with
the modiir abstract, and no instances ean be created from an abstact las. Let's
sce how the abstract Student class is defined.
[— steernce ct
seeaent (
protected ine(] testy
public student) (
fend (tna nae"?
,
public Stusent (sting stuseneane) (
758 cnapurts
inant
Sirs
shesmnaindrbahin
public sering geteoursecrade() (
,
public string getnase() (
,
public int getrestscare ine cestionver) (
‘return cect (sestitunber i];
,
public void servane (string rewsane) (
,
Tese[eeectineer 3] testacarey ne See
,
,
An absiract method i a method withthe keyword abstract, and it ends witha semi
‘colon instead of « method body. A clas is abrrac ifthe class contains a abet
method or dors not provide an implementation ofan inhented abstract metbod. We
say 4 method 3 np!onenea if ha a method body Ia subclass has no abezact
tmetiods and no unitmplementedinberted aburact methods (and does not include
the keyword abstract in its class definition) then th subelass tno longer abst,
and thet instances can be eeated
‘An abstract class must include the keyword abstract in is definition. Notice
that the abstract class Student has an incomplete definition because the class
includes the absract method computeCourseGrage tht docs not have & melbod
body The intent ist let its subelasses provide te implementation ofthe compute
CouneGrade method. Ifa subclass docs not provide an implersentaton of the
Inherited abstract method, the eubelat also an abstact class and therefore, 20
instances ofthe subclass can be rested, Since an abstract class can only make sense
‘when tis a superclass, we frequently use the term srt superclass
ace rite thatwe cannot
an abstract class Ifa assis abstract
cass but not being able to eate an
ass sastract The intent of an 3
subelsies and leave some portions tl
bythe individual subelasses We
las for which we cannot create ant
instantiabl class by cefnton, but the
able classes, for example the
‘define anoninstanabe dass, then sigIn ¢program diagram, we represent an abstract class by using the keyword
sbswact. The Student abtract superclass is drawn a
(eben
aze 2: Student Does Not Have to Be Undergraduate or Graduate
For the second cate, where @ student doesnot have to e a rade or sn under
szaduate student, we can design clases in two diferent ways. The fs approach is
to make the Student class nstantiable. The second approsch it leave the Stent
‘lage abstract and 28a third subclass, 54), OtherStuden, to handle « student who
is nether a graduate nor an undergraduate student, Let's all students who ae oe
ther graduate nor undergraduate udentsnonrepular student Let's assue futher
thatthe noncegularsudent wil reeive a pass prade ihe or his average es scare
's greater than or equal to 50. With the fst approach, we dein the Student cass as
merase student
Protected an0 {1 test
public stasent (1 ¢
entero nase")
,
public student (string studencwane? (
test ‘new nt [SUM_O# TESTS];
,
> puntte void computecouresccade( (
gor (ine = 3) 4 < NOME ‘
total Se eeze (4)
,
SE (eotan/womor_tasts >= 50) ¢
balee tl
Panton
,
public string getcourseczede() (
,
public string getnase() (
,
public int gettectseoze ine Lesttunbes} (
‘eeturn teat (eeetinber 2]
,
public votd secvane (string nessa) (
,
Public void setTertscore (int testiunber, Ant teetseeze) (
eet eestiunber 1] = Lestseos
,
‘The cles is no longer abstact, and we can create an instanceof Student to tepre~
seat a nonregola student.
‘With the second approach, we leave the Student cass abstract. To sepresent
nonrgular students, we deine hid subclass called Otherstudent as follows:
class othesstudent extends student
public void corpurecesrsesradet) (
estes 200) (
Ae (coal/MnLor_teeTs > 50)
,
>
Figure 13.7 sa program diagram that inciodes the third subelas.
‘Which approch is beter? Theses no easy answer It ll depends ona given
situaion. To determine which approach is beter fora givea situation, we cam ask
‘urceves hich approach allows easier modification abd extension. Consider, forFigure 13.7 & program dagram ofthe asad supecss Student ad is ee subchsses
example, which approach wil facilitate easier modification if we have to ad new
‘ype of seudnt, 3, scholarship students. Or consider the ease where the rule fot
assigning a course grade fr the undergraduate and graduate students is modified
Sey. they become the same
Finally, ot all methods canbe declared abstract. Specifically, private meth
os and class methods (fall visibility modiers) cannot be asta.
aoe
Ban a ae el
1. Can you ceate an instance ofan abstract clas?
2, Must an abstract las nce an abstraet method?
3. Whatis wrong withthe following declaration?
758 chapartd stecanaandPaention
13.7 | inheritance versus Interface
Java interface and inheritance are language features used to support object-oriented
‘modeling. They ae similar because they ae bon use to model an IS-A relation
‘hip. Consider, for example, the following las definitions
rk (
,
class Savingohecount extends Aceaunt (
>
‘We say “AddreuBookVert isan AddreutBook” and “SvingiAccount ian Account.”
‘Because of this simlaity, beginning programmers often have some difhculty in
ferentiting the two clearly. Although they ate similar, their intended wses are
uit dfeceat
‘We use the Java interface to share common behavior (detned by its aetract
methods) among the instances of unrelated clasts. Aad one ease ean implement
rmuliple interfaces: For example, we can define 2 single Person lass that imple
‘meats multiple interfaces such a Driver, Commuter, a Biker
‘We use inheritance, on the other hand, fo share common code (including both
ate members and methods) among the instances of elated clases. Anda single sub-
class can extend at most one superclass. For example, the GraduateStudent and
UndergraduateStudent classes are subclasses of the Student class. the Truek and
Motoracle classes ate stbelasses ofthe Vehicle clase, and sofort, The sperelastes
Include data members andor methods thal are shred by the subclasses The IS-A,
telaionsip tha exists betveen a subelass ad ite superclant 8 specialization, a8
{ruc ita specialized Vehicle. Such a specialization relationship does nok exist wth
the Java interace
<0 Use the Java interface to share common behavior. Use the inheritance to
© “share common code.
an entity Alsaspecelzed form of anther entity B, then model them by
sing inheritance DedlereA.asasubcassofB.“eden
124 savphetipmet 759
‘We must be caefal not to mix up the use of service clas and inheritance
Beyiners often make this mistake. Suppose you want o define class that maintains
liso muse CDs. Which of the following two definitions is a beer design?
plies ¢
,
,
The frst version ues inheritance and defines a subclass of ArrayLi. The see
ond version defines a data member of type Avrayist Te rt version 8 a misuse of
inheritance. When we define a subelats A of superclass B, we must atk ourselves,
Is AaB? Can we say CoManager i an Arrays? No. The COManager i not
specialized version ofthe Arayst. The COManager clas simply needs to reuse
the sevice provided by the ArrayList clas. Ths, the second version ithe proper
desigo, We eal tis typeof code reuse co reise) compovion
Beyond the conceptual problem. deining the CDManager class asa subclass
of Araylit hat practical weaknesses, Because its a subclass, the cient of the
{CoManager class can cll any methods defined in the superclass Arayist But does
it make sense forthe client to all the method such at ensureCapacty? Another
weakness isthe diuly in changing the implementation ofthe CDManager cas.
‘oppose we nce to modify the data structure clase fom AvrayList to HashMap for
beter performance. With he inheritance approach. any client that uss the inert.
methods of Arayist needs to be rewniten, With the composition approach, the
‘lie! thal uses only the methods detined forthe CDManager class wil continue fo
‘work without change, The change made from the Arraytst clas to te HashMap
lass is encapsulated in the COMnager class and docs not affect the clients
Computing Course Grades
Lets develop a program thatilustats the use of Student ané its subcses Graduate.
Student ané UndergraduateStudent. The program il input stodent ata rom a use
designated text fle, compute the courte graces and diply the rests We assume tne
teacher may have kept his staden grades in antebot instead of manual computing
the grades witha penelland cakutr he enters data int a text file and uses Ps pro
17a to compute the couse grades. Another possible scenarios thatthe teacher Uses
{ome kind of ppirton software that allons him te maintain udent records. Suppoee
thir applcavon doesnot alow the teacher to ure eiferent formals or computing the
couse grades of undersadvate and graduate students such 3 eae the teacher can
IB.B sample Developmentcrmned
‘racuate an graduate tents asing the diferent forts Using txt les oat
{ata om one aplcavonto anther aplatonis very coriman technique insane
‘paleations.
fo focus onthe use of inhetance and palmerphisn, we will adap the basic
and ovtout routines eset as ners to mplement tem diferent. xerese 9 aks
you to save te data to an objec fle an Exerse 10 asks you to use the Seanmer css
fering
Problem Statement
hte an epplicion that reads na tet He ergnizd inthe manne shown
below and dsplys then course grades. Thecouse rads ar computed di
ferent for the undergraduate and graduate studers based on the formulas
litedonpage 77. The nut tore formats follows
+ Asin ine tated forinforaton on one stent,
where cType> designates ter a graduate or an undergraduate student
“Name> designates the student's fist andlot name and designates
theithtertcore
Endofnpuis designated bythe word END The case ofthe ete
sinsigicart
overatiPlan
1. Readaninpettext fe
2 Compure the course grades,
3 Printout the est
Figure 15.8. sampletex fe containing adel names anaes sore atthe beginning of ne124 saepheipmet 761
Tread a text fle, we wil use the standard fle VO objects Fle, FlleReader,
and BufferedReader. To compute the course graces we wil se the Student Under-
graduate, ane Graduate cases defned eter in the chapter Te formulas for el
unting the course grades ae define in their respective eomputeCourseGrader
methods Since the input fle is 2 text fle we must create ether 8 Graduate or 39
Undergraduate object for each Ine of input, 50 we wil be ble to cal its compute
GeurseGrades method. To store the created student objects (stances of either
Graduate or Undergraduate, we will use an aray of Student to gain more pracice
fon sing ays:
To fects onthe inheritance and pelmorphism topics, we wil use two heer
tases. The fit ir he OutpiaBex css which we use to dsphy the course grades ane
save the result ack to er fe We uses print ne println methods for output ands
{aveTofile method to save the data to «ton fle The saveToFile method saves the
Complete ertn an OutputBex'e a designated eth le sed exists, then he oi
Ina contents ofthe fe wl be replace bythe text currently shown he OutpUtBax.
(Often, we need the capably fo save the text niferent format For example assuming
‘he stent iformaton clades the stent ID number te teacher ay want to
‘only the nt four digs af he ID numbers ane te al course grade so the res cn
be posted we wiht save the textin a diferent formas ene have to implemen ou
‘um method with such capability,
“Te secand helper lis the Main\Window ls. We vil narne our main class
ComputeGrades, and as another example of inhertance, we mate a subelass of
MalnWindow. The MainWindow steel a subclass of JFrame and has the functionality
of pestioning sea the center of the scren farong ether features We cover the
Gets of ubcasing the JFrame css in Chapter 14
Heres our working design document
Design Document Conpucecrades
‘cae Purpose:
Compateccaces | Thetopevl contolobjecrmanagesoter objec
inthe progam The cra uncer ofthe helper
fhsshscn ao. The dts ithe nstarile mah
oarpatvox [An cutmcttox objects ted ie ply tempt ata
and computes couse gods.
student, Under | Thee are aplication ngicobects for students. The
Seaduacestudest, | Srusen daerieanabaract perce
File, Pseneaaer, | Thesear objec necesaforeading da from
buftereatenter’ | | tentie
IB.B sample Developmentcrmned
Tan apaon
Taaecinte] [Comptoir Tae
Figure 13.9 An objec gram ofthe ComputeGrades program
Figure 13.91 the program diagram
"Now lets thin about the methods of ComputeGrades. What kinds of public
methods should the ches suppor? Since a ComputeGrades object is & topevel
“onto objec Let's define a single public method eld proessDatate cay out the
‘thre main asks Themain method of ComputeGrades wil clthis method
public static void main(stringt) arse) (
Conputedzades qradeConputer = new Conputeczades )
‘qradeconputer processDeta(l?
,
‘he procesData method wllook something Ike thi:
ehsa.cetieible(erve); //zake this main window
fsurputiog.setVisuble (erue)7/ ard an susputbor vieible
Desleen succens ~ resaDatat
24 (euccosed (
conpureaade )
prssenecuie()?
y alse (
,
The readData method retums true the inout dts are readin comet from
«tea fie andthe aay of Student objects s propery erated. Our woking design124 savehepmet 763
ocurentforthe Computesrades assis as ellos
Design Document: The Conputecrades Class
Visibity | Purpose
pubiue, | Crests andintitae the objects wee by 2
procesepats otic | Diplysisetfand caries out thee main tsk
TesaData private | Opens and eds dita trom ate fe nd estes an
atayof Sess objects om heinput ata the
Speraton success reams ese
cconsucescade | private | Seanthroughthearay of tusent objecteand
computes the couse grades
princtesute cerivate | Prntroutthe tudentifomation aang wih the
Wi wlldevelop he program in five incremental steps:
|. Startth the program skeleton Define he skeleton ComputeGradescsses.
Implement the prntResult method Define any other methods necessary 0
implement printResule
2. Implement the computeGrade method Define anyother methods necessary to
Implement computeGrade.
Implement the readData method Define any otter methods necessary to
implement eadData,
5 Finalize and look or improvements.
\We fer the implementation ofthe hardest method readData uni th st Some pro
grammer pele to deal with te hardest aspect of he program fest and here stl
"le for ordering the implementation steps You should order the sepsn 2 way with
tuhich you are most confortable However, this does not mean you can implement
‘the methods a random, You must always plan the implementation steps carefully 0
the sep follow a logical sequence Fr this program we start with the ouput routine
rove ana twhenteting other methods insteado defining temporary land hr
way) output routine fortexting purposes
Step 1 Development: Program Skeleton
saepi Lets begin with the data members and the constructors forthe ComputeGrades chs.
hoe Wevillstarc wath the folowing data member
private student( 1 rosters
isa sraightorward operation create the fst four objets but we need think
se about the restr ery. How ig should the ray be There ore several poses:
‘reat an ary ofan arbitrary saga. 25.
2. Lerthe programmer pas these nthe onstucto
5. Donet create inthe constructor Moly the input tect le to Include the sizeof
anarayinthefistline
‘Option 3s not atractve because it will equire a change in the problem speciation
Moreover reiting these information inthe input fe wl put tof burden an the
‘ser ina mast go aver the text fle and count the numer fines thee contains Such
[burdensome ask shoul be lft computer So we wilimplement options 1 and 2
‘the data cannot fi int an aay ofa predesgnatd shen we will use the technique
_dscussed in Chapter 109 expand the aay. (Notice that we are using an aay where for
edogogia reasons We ean we a fst such a5 ArrayList or LinkedLis instead Using 3
Frtfor maintaining roster left as an eerie)
Wececlesonstant
ind declare te two constructors at
‘enss (OEPADLT_sIZE)
see) (
,
public conputecrades (int arcaysize) (
aupert)) (Jan explicit eall te the cuperelase constructor
lsutputon ~ new outputbox (thts)
foster = mew Student (acraysizel
,
Notice that we cant crest infil eReader, and bufReader until we know the actual
{eto open, We wl create these objects none ofthe methods we deine later,
For the steleton program, we include temporary output statements nthe pate
‘ethods to vey that hey are cle coved nthe ght oder Hees the halen124 Seohbeene
lass conputesrages extends wstnitnaay (
uw
private static final int OEPAULT_SIZE = 257
private student) raster:
public conputeceases() (
‘chi (OEFAULE_ S222)
,
public Conputecrades {int azzaySized ¢
superth;// an expiiest call to the evperelase eonetsuetor
sestputton = naw ostpstBox tena)
public static veld main{stringl) argo) (
Conputedrades yradeConputer = new Campsteczedest) +
{radeConputes.processdeta(h?
,
public void proceasbatat) (
Ghia. setvieioie eee);
sutpuraox.setvesuble (erse)
£6 touccesed (
conputesrade ts
prineresule
yeast
foctputbox.princin(*Psle Tnest Eevee")
,
,
private void conputeczade() {
outputBon.printla(*Tnsige cemputeGrade’); —//TEHE
,
private void printtessit () (
outputvox rrintin("inside printiesuien); //s280
Pe
private boolean sesdbeta() (
We execute the skeleton main case ComputeGrades for veeaton, When ie
me execute we wile the top-level ame window (ComputeGrader) and an OutputBox
{ppeating on the seen andthe felling messages the Output
Step 2 Development:Implement the prinResult Method
snepi__ nthe second developmen step.e ade rutne thal laces the result nan euputBox.
Berjy—_Teimplement and test ths method, we need to crete the rster aay. wil ined
temporary code nside the readData method to build test ester ary Wecan use fr
loops asin
for int =o; 15) to
hefothatline Eoater[i] = new Undergraduatestudent { 95
IUNMRgelige Hester] eetNane( Unuergrad #7 + 1 93
koster[i] sattestseore(l, 704 191
Fasterli} ectteatsearet2, 15 4 3})
Posteri} cesreatseare(, 804 3})
,
for (int i ~ 15; 4 ¢ DEEAULTLSI25, ise) (
peseenshhvoine EOOUCELL] = Sew Geadsatestadeat (7
meyiegaate Fostertil.sethane( "Gras #1 ADF
eoater[i] setTestseore(, #0 4 49)
Fosters] eecteatseare(2, 65 + 3})
Fosters] cezrearseore(), $04 3})
,
to creaea temporary roster or testing purposes124 Sephemet 767
Now les design the printResult method When this meted is called we have
the restr aay built The method scans tough the ary and retseves the student
at, using the getName, getCourseGrade, anc getTestScore methods. Expressed in
prcudocode we nave te fllowng
output the nane of rosterti}y
output the tect ccores of rester(i}s
output ehe course grade of roster {ile
ow should we terminate the loop? We should tele fst thatthe roster aay
may ermay net be fll For examale ts default izes 25, but he actual numberof ele-
rmentsmay be ess than 25 so using he alueofresterlength will et work Sucerester|
isan aay efebjects one possible way to expres the leep fas olows
weiie (cootertiy = muta) ¢
(one problem with hs whe lop shat we must have at last one empty slot nthe
airy forthe oop terminate corely. We can improve by using the length vale 25
while (6 < roster.tength 66 rostertt] {= mula} ¢
,
we use the foreach lan, then we have the fllowing
tor (student 2: raster) (
sf(e- pull) Breaks
‘Another posit sto ep the count which we set Inthe readData method.
‘Thiscountvilbeadata member oftypeint. Lets callths coun vaabe studentCount
“Then the processing loop Becomes
for (Ant £ = 0) £ « studenteounty 60)
We will adopt this approach because having this count information i useful for other
purposes. For example f we want te compute the percentage of students pasing the
‘Coutse.we can se studentCount to compute Mwe dant have ths variblethen every
IB.B sample Developmentcrmned
time we need comput he parentage we have find ou the numberof tens in
therester ary.
Finally to pint out student information so the data wil agn propery we wll
‘output the convol character it or ab. Fora somal outpt lke th sending tabs to
‘utput will work fie Fora more elaborate output we can use the fermating technique
decursedin Caper,
Heres the step 2 code. Notice we ade the declaration fora new dara member
#2920886 ssudentCount, ane he dota members alzed oO inthe constructor
Computeczedes extends Mainhinow ¢
public conputeccades (ant seraysize) (
private void printkessle() (
for (int = 0) 4 < ctudentcounty 124) (
outputbox print. (roster [i] geenane )}7
vvestnun <= student NOK OF_TEaTS;
Tesenomesy ¢
eurpotton.pri + eoater(t} gertectscore (testa);
outpathon.printin("\c" + coster{il .geteoursetrsde());124 Seohbeones 769
boolean resabata) (
box-prinein(*iassde ceaabcat);//EMe
for (int 1 = 0p Sc 15 HHL
rorter{s] = new Grdergraaustestudent():
parces(s]setare(oraergese # "+ 307
soster{id settestseare(t, 10+ 595
sVaetTestieore(2, 80 + 5
Forter[i] setTestsesre Qs, 90+ iy
,
for (ine 1 = 25) 4 < oREAUIT_eTaRy 144)
forter{i] = new crasuatestedens ()
sarees (s]-sethare('orss P "> 3})
soster{s] settestscare(l, 40+ S97
SecTestseore(2, 35+ 2)
secTestseore(3, 30) iy
,
aepatet
a
Wi verity wo tems inthis step. Fst the temporary readData method includes
eating student abject ond caling ther methods. Core executon wl very hat
twe are including the corect student cases and using ther methods properly, Second,
the printResull method shoule display he output 35 intended Since me have not
Implementee the computeGrade metiod we wil se fou asterisks forthe course
grades We have trun the program several ines and adjust he eisplay format. Ab,
Ris important to try aferent vues for names and test rarer Before moving tothe
Step 3 Develepment: implement the computeGrade Methed
The funcuonaiy of computing the couse grades is embedded isi the student
clases specially, inside the respective. computeCourseGrade methocs of the
GraduateStudent ad Undergraduatestudent classes. Therefore all we need fo doin
the eomputeGrade methodist scan trough the roster aay and cllthe elements
‘computeCourseGrade method Ths mpl ea dec res of polymorph
step Seade Here the listing. The only adios the computeGrade method
Conputecredes extends Waisiindow ¢
for (int i = 0) 4 < studentcounty it) ¢
soreez|s) conpuretocsaeceade
,
We repeat he same testing routines of step 2 Instead of seeing four asterisks for
the course grades, me should be seeing correct values. To make the verction ea),
‘we can set the feed test sore for all dents, Make sre you asgn fest scores that
‘wl eu in students both pasing and not pasing, Don forget to ty extend cases
‘uch a 07 for l three et scores What about negative test cores? Wil the Stacent
Clasies handle them correct? If we idently sevious problems with the Student
‘clases at this pont we may have te suspené our development untl we comet the
‘Student clas,
Step 4 Development: Implement the radiata Method
caopa We ill now design the core function of the chs the readData method. We can
seep express the over ogi of the metnod in pseudocode as124 saepheipmet 771
Vie wll use 2 Filechooser object fom the standard java.swing package tet
the user speci the fief the usr cancel this alo, hen ull retuned thi x,
wwe pint outa err message and stp the wer species le.then we pas his nor
‘maton toa priate metnod bulldRaster, which wil ead dt rm the designated le
{nd build the ester ary
The buildRester method wil ead one line of data fom the designated feat»
time, and fr each ine of data, creates an appropeate student object an instanceof
GraduateStudent i the type is G and an Instance of UndergraduateStudent I the
‘ype is U). The counter sudentCount is cremented by 1 afer each ne ie presse
When te ne contains the terminator END, the method completes its execution the
data in 3 ne do not conor fo the designated format, then the ine Is ignated The
method expressed in preucocode allow
while (apne) (
$6 (nw se E001
Student = ereatestudent (ine);
asad tay Se (steaent t= mula) 4
Fooled er A rorcer[atogenecaune] = stedents
,
,
Caton lotecertion a)
Wie use the tyceatch black because the creation ofthe BufferedReader objec
butRender rom a siren flare coud reult in on exception, We can use the Scanner
‘dus intend ofthe FleReader nd ButleredReader cles, Wecreate Scanner objet
bypasing a Flle abject to he constucton
‘The ereateStudent method accepts 2 String argument which sone ine of he
inoutfle andretumean instance of either GradunteStudent or UndergraduateStudent
Aepencing on the toe specie inthe nef teres an err inthe Input ne, then
‘estestudent returns nl nsead of terminating the whol program, we wilsimply i
nove thelines tat do nat conform the species forma.
IB.B sample Developmentcrmned
tna very simples frm, the ereataStudent method looks ite thi
Af teypeceauats (onmeR_cnno) |1 Eype-equais (RAD)) (
nearer season” neysregensseabars ( anpurLine 17
a ) else ( //isvalsa type 42 encounteres
,
“The tp statement requies ut extract the rst iter inthe input lin (Sting. How
should we dof? The newStudentWithDate method, which cestes an instance of
GGraduatestudent or UndergraduateStudent and assigns data to 1 ao regues
{7 operation fo extracting elements of cata fom 3 single line We ean wit our
‘wn sting procesing rutin to pare a given ne and extract éata on ype name,
fre tert scores, but there» Detter sation We can aie > sanaare chs called
StringTekenizer ‘rom the javatt package We wil take 3 quick detou" to explain
‘his eas sted of using the StringTokenizer ls couls use the paters-matching|
{echriques withthe Pattern and Matcher cates et ancther approach st crete 3
‘Seanner object fr eath line of text, bu ths wll result n creating s3y 1000 Seanner
‘objects when the impr le conans 1000 Ines of text. This i iefcent The use of
StringTekenizer dass 's more appropriate in ase sucha hs, here we nee to ex:
rac tens fom a given sting And, we only need to create exactly one String
Tokenizer object o process the put fe.
1 ssngokenser abject wid extract tokens rom agen string. tokens 3
string of enaracters sepatste by dele chorate ar imal dliiters Ary character
‘an be designated a «delet, but space ithe most commonly ued dente 89
‘ete. StrngTokenizer object uses whitespace (lank tab ne Uno tur) a
elites Heres an ample The folowing code
sexingTokensaer parser = new stringToxenszer(inpurstring)
Systen-out privtin (parser.nextteken (0);
,
willprint out124 saveheipmet 772
‘The hasMoreTokens method returns true if there are more tokens remaining in
parse, andthe nextToken method returns the nex token in pase. The nextToken
‘method throws a NeSuehElementExceptionftherels no toxenoretun Pleaserefet
‘03 Java. ference manual formore information on String Token
‘up programming the functionality
thing that has been done alread.
justfor beginners Whenever you
'2 commen programming tas fst
also can ask your classmates,
ce. They may know something. You
‘ava APL reference manuals £0 you
staneatd classes The key is alvays |
Now les get back to the design Using a StingTokenizr abject we cn express
the eenteStudent method at
sngtokenizer parser ~ new fcsingtokenizer (Line):
SE (oypevequate (EMERGED) |) typevequale (RADI)
sticece = aewstudentwsehbata eypey patees) +
) alee { //snralid type ie snesuntered
) eaten (Nosuensierentsieeption e} ( //s0 coke
A prate newStudentWithData method accepts 2 String shat species the
‘ype of student and a StingTokenizer object The method creates an instance of
IB.B sample Developmentcrmned
LUndergraduateStudent or Grasuatestudent and assign dts to the object by cling
‘the SringTokenizer object's nextToken method repeatecly:
et
{AE (eype-equala (UNDER eAAD))
segsene ~ new Urde=geaauatectacent ();
pels t
student new Gradsatestudent (17
,
) eaten (exception eb ( //cneoH By Be
>
‘Our design document fr the ComputeGrades class now includes three more private
methods
Design Document: The Conpucecrades Chass
Method vusibity | Purpose
pultenoster private | Reaésone ln oft fom the designated le
atime andor ech Ie of data cates 29
Sppropnteudent object the dain ie do
not corform tothe designates erat hen thelne
oon pesvate | Creates a student bjt by cling
ewatvdentiachDatai the ypein tempat
Ines or succesful retusthe created
studenvotherwse recuse!
resstudentwicnpata | peivate | Createsan instanceof Unde=gzaduat Student
orcraduavest cent ane aeigne dita tothe
sbjetay caingthe sr
ext Token method peated124 Seoheimet 775
ephente Heres he complete sep coe
File: conputegraden. Java
”
seport jave.to.ts
import Savax.ewing:*7
class Conputesrades extends Yalniindoy (
private static fined String EMD_OF PILE ST& =
public Conputecrades() (
thts, GEPROIT-ST22)
,
public conputesrases (Ant scraysizel (
superthy J) sa explicst cali Lo the eupezelass conetsuetor
ovtpettox ~ new Suepucsox(ehss):
recrer new student farraysize);
public static void gain{stringt] arse) ¢
Conputetrades gradeConputer = new Conputecrsdas ()
qraaeconputer.processData 0s
public void proceasDatat) (
setisetave terse)
octperbex aetvesible (2x38)
eee
boolean success = ceadbatot)s
64 touccesed ¢
cowitesrade 0s
srinenesut 0)
yalset
feurputsex.printin(*Pile ropu Recor")
,
,
private boolean puildRoster (string Citesane) (
ery ¢
TnPite = naw rite cestenanel
Eiloneader = new Pileteader(inPLle) 5
butkesder | = new Buftereateader(Zileneades):
ste done)
SnputLine = pueReader. readline}; //sead one “ise
Af (Anputhine.equalstgnerecase (€80_0F PELEETHI) (
ase
Suident = exectestudent {inpuctine)¢
S€ tetudent $= nll) (
pees [studentCoust} ~ students
,
,
buckesder.eloze
,
etch (roException eb ¢
,124 Sepheimet 777
,
private void conputecrode() {
for (ine m0) 1 studenteousts £61)
soover[{] eomputetossseseade (7
,
StringTokenizer parser = new StringTokenizer (Line);
tet
ype = paraae nant Token (4
Af (2ype.equale ENDER GRO) |) typecequale senor) ¢
student = newitudentwithoata(eype, parser};
‘
,
) eaten esuentienentsxeeption e} ( //s0 corer
,
private student sevitudentWichoate(steing tyre,
‘SteinaTorenizes parser} (
Ae (eypeequala (UNDER cRAD))
tudent ~ new Uecergraduarestscest (1)
1) ase ¢
,
Suring CizstName | ~ parser extToxen (17
String lactMiane = passer sextToxenQ)¢
or (int testitin ~ 2; ceszihun © student im_ov_testay
testiumee)
eee
svodens cet testseore (cectiin, Integer.peraetnt(
poser nex: Z0%en (1);
,
Y eateh (Exception «) { /Jeither parser nextToxen) oF
UPirvegersparseiat on) Pht@Mn eeept son
,
private void prinenesstt() (
for (Ane 1 = 0) 4 < studentoounty 444) (
sutptaox prine.(recter{i) etwane())
Zor (int testiun = 1; tectitin < student sin, oF reste,
Testhnes) ¢
int ("\e" + ronter{iy gee Test eon
teesenun):
,
oorputBon.printin(™\e + restart] getCouseacrsae ())
,
private boolean sesabsts() (
= cliecheoser.showopendiateg this):
se (returnval == JFLLechooser APPROVE SPTION) (
STD eisethoocer getseiectedeie() gesabsalatersth()7
A€ (eitename t= mol) (
reguit = boildRoster (ritename)ry Wie run through a more complete testing routine inthis step Wie need tran the +The third visibility modiir isthe protected modifier.
program forvarious types of inpur ks Some af he posible le cantents ras ollows + Teno instances ace created fom «superclass then define the superclass as an
saat clase.
Sup Asses) + Polymorphic messages el us tha the method executed in response tothe
Teste Purpese message wil vary according to the clas to which the objet belongs
NG TScieca a hae +The int statement in constructor of a subclass must be a call toa
‘tidentnformaton with conseuetr ofthe superclass Ith required statements not made expliiy,
attire arse then the statement ocll the default constructor ofthe supecclass is inserted
utomatically by the Java compile.
Fie Sezoetet Tegan and pra maids +The standard lass described or used inthis chapter SringTokenizer
ay Tain baka a Ce
ase prope. superelats and subclass abet superclass
Flewihmorethanasenties | Ten'vatreadOata ana supporting methods inheritance sbetract methods
han she case ere the numberof erie Inheritance and constructors polymorphism
ee ae inheritance and visibility modiders inheritance versus interface
prsteaosiaraiiestatmaiaitotee
progam Asalway, we wilfinaize the program by correcting any remsining ever incansiseney, - a
TSE” Sniathelmeods eso ok or inroveetn he st ep Onelnpreveen Review Exercises
ae ancient eat ae neces 1. Consider the following class definitions. Kent invalid statements
bullaRovter ananewStadentithData method ate close the maximum. fave nose class car (
the method x geting longer the coding sage we may wantto rethink our design For peblie string make:
‘romp the bullRester method becomes foo bg then we can deine sre method Feevected int" weights
{hat akes ae of partion ofthe method such as moving he then
the method to new method
‘ne problem that remains which would have been identified In step 4 testing) ,
the missing method or expanding the ester ary when theinputfleinclades more sto
enc entes than the set default se of 2, We lave ths metnod az Exerc 3, We ako
Tesve some ofthe porleimprovernents a exerces,
class Electriccar extends Car (
public Flectriecse() (
>
public Flectriecar (Eleetriccar ear} (
+ Inheritance and polymogphisin are powerful language features to develop Getgne 7 caecvetgte
‘extensible and modifiable code. ‘color ew String(car-coler);
+ Inheritance mechanism is used to share common code among the rlated
classes >
‘+ Inheritance i ferent om the Java interface, which ie uted to save
‘common behavior among unrelated classes. ,class Testvats (
public aeacie void main (Stringl stg2) (
pysleccae = now elecestecac();
2. Consider the following cass deiniions,Idently which cll to the
‘consiucter ace invalid
public | string
private Car (String make, int weighty String cole) ¢
public ea 0) (
‘chia ("enenowny Ly
,
suniten:
ws EuectrLecar extends car (
ena)
private Electeictar tint charge) (
rupee
clase Testiain (
public aearie vosd main (Stringl 292) (
ytart new ca503
Pycard new Ea5("Ford", 1200, *Sreent)
>
5 How would you mouliy the ComputeGrades sample program if the formula
{or computing the course grade wee dierent fr lreshmis, sophomore,
jon, and senior undergraduate stadents? Would you desi four
subclasses of UndergraduateStudent? Or would you modify the body of
the computeCourseGrade method of UndergraduateStudent? Discuss the
ror and con of each approsc,
Level 1 Programming Exercises
4. White a program that creates an ArrayList of pls, An tm in thelist either a
og or & Cat. For each pt, enter its name ae type’ fr eat and‘ for
dog). Stop the input when the sting STOP is entered forthe name. After the
Inputs complete, output the name and type for each pt inthe ls.
'5. Repeat Baercis but this time group the outplby printing out he names
ofall eats fst and then the names ofall dogs,
Level 2 Programming Exercises 4%
6 Modify the 005 class to include «new instance variable weight (double) and
the cat clas to include a new instance variable coatCoor (sting). Add the
comespoading accessors and mutator forthe new instance variables.
“Modify Exercise 4 by inputting additional information appropeae forthe
‘ype. Fist you input name and ype, a before, I the (peo eat then inp
ste coat color I the type is dog, then input ie weight. Mer the spi
Complete, output the name, ype, a coat color forthe eats ana the rare,
types and weight forthe dogs
7, In the ComputeGrades sample program. we st th default sizeof the roster
ray (025, Modity the program 10 the ie of the aay will be increased if
the input ile contains more than 25 students. You need to ada method that
expands th anay, ay by 50 pezeeat The technique to expand an array was
‘discussed in Chaper 10.
1 Modify the ComputeGrades srmple program by using alist (reais ot
Linked) instead ofan ary.
9 Extend the ComputeGrades sample program by storing the roster amy using
an objec le. Give an olion to the wie read te data fom a tex ie (his
Jshow the original ComputeGrades works) ofan object le. Silas, ive
sh option to the user to save the dita toa texte or an object le
10, Mosity the ComputeGrades sample program to input the data from a text le
using the Scanner clstinstad of the FleReader and ButferedResder clases‘Use the ab character) asthe delimiter: You erate one Scanner objec or
the whole file. Assume the dat in the i is comet.
Level 3 Programming Exercises si
11 In the Chapter sample development, we defined the DrawableShape class
that includes a method to draw one ofthe three possible shapet—sectanle
rounded rectangle or ellipse, Modify the DrawableShape class asa super
lass ofthe thee subcastes Rectangle, Roundedecangle and Ellipse
‘The actual drawing ofa shape is done by the drawShape method debned
in each ofthe thee sublasses. Using the DrawingBoard helper class
rom Chapter andthe four elses defined in ths exeeise, write
screensaver program tht draws 10 rectangles, 15 rounded rectangle,
and 20 ellipses of various sizes. A shapes will move smoothly aross
the acter,
12 Suppose you have alist of Dog and Cat objects from Exercise 6 and want to
Find the average, minim, and maxims weight of dogs. To compute hese
vals, you mast sean the whole ist, Ie would be more efficent if you could,
pet the fesuls by wavering oaly Dag abject inthe lst One approach 0,
{cheve ths improvement isto eeate another list that inches only Dog
‘objects (actully references to Dag objets). Here's an example:
Repeat Exercise 6 but this tie cea the addtional dog list. Then find the
average, minimum, and maximum weights ofthe dogs by uaversing the
og ist
18, Perform th input routine forthe Dog and Cat information as specified in
Exercise 6. In ation to creating a main list create separate cat and dog
lst (eve Exerese 2) Alter the lita created, allow the end use oad
ox remove information, Display the fellowing men choices:
Panton
Allow the usr to remove the information by specifying the name (assume
thete are no duplicate names). When adding anew eat o a dog, input the
corresponding data values. Make sure o update the ists accordingly when
fading or emoving a pel. Repeat the operation uni th user wants to qu.
Notice that we use 0 for the men choice Quit By doing thi way we don't
have to change the eode for guiting the program When We add mare men
choices late,
Development Exercizes
For he following exercices, use te incremental developmen methodology to
plement the program. For each exercise, identify the program tasks, crete
fa design document with lac descriptions, and draw the program diagram.
‘Map out the developmen steps atthe sar. Preset any design alternatives and
justify you election, Be sure to perform adequate tenting a the end of exch
evelopment step,
|, White a personal finance manage program that maintains information on
your bank accounts Incorporate these rales:
x the savings accounts, you can make a maximum of three
vwthérawals in a month without incurring afe. The bank charges
S100 for every wihdeawal aller the third
+ Rorthe checking accounts, the bank charges $00 fr every check you
ite for he fist 20 checks (he, withdeawals in a month Aer that
there will be no charge
‘You should be able to open and save account information to ale. You
shouldbe able to list all transactions ofa given account o of all account.
Inhide eppropriste ments o sleet the options supporied bythe program
Consider using the Date class to record the date of tansactions, The Date
class som the java ut package, Peas refer toa java ui eference
‘anal for information on this cas,
45, Extend the adaiess book sample development from Chapter 10, Instead of
managing a single ype of Person, incorporate adéitonal pes of persons
sich a PersonalFrend and BusinerAsrociate, Deine these clasts as
subclass of Person. Design carefull o decide whether the Person class
willbe an abstract clas.
16, Consider an aset-racking program that will tack four types of ase:
cleevonic appliances, automaales, funiture, and compact isk What
lasses would you design for he progsam? Would you define four unrelated
‘laces or one superclass and fou subclasses? Ifyou design a superclass,
wills bean abtact superclass?
17, Implement the ase-racking program of Exercise 10. Allow the user oad
roti, and delete eleetonseapplances, automobiles, furniture, xd
‘compat diss. Allow the user alist the assets by category and earch for
sh ashe by i sril number18, Extend the assetsrackng program of Exercise II by adding an objet UO)
capability
19, Write an application that reads daily temperatures for 12 months and allows
the user to get statistics, Support at least thre options: monthly average of &
ven month, yearly average, andlowert and highest lemperatires of piven
Ihonth, Use aten te to store temperate, Aline inthe tent file contains
daily trsperatures for one month. The fis ine in the textile contains
temperatses fr January he second line, thove for February, and so forth,
‘Ure StringTokenzer to parse line into temperatures of type lot. For «data
structure, consider using either an array of Month or a two-dimeasional
tsray of flost, Month ie class you define youre,GUI and
Event-Driven
Programming
“a T. sample programs we have writen so far used standard clases such as
Scanner, PrintStream (Syitemout i a instance of PrintSteam), and others for
sbanling ser interface, Theve standard classes are conveniea and adequate for 3
basic program that does not require any elaborate user interface. For example
When we need to input 4 single imieger vale, calling the nexcht method of
Scanner once to read that input is appropriate and eecive. However, when we
‘need to input, sa, 10 value fora Stent abject (eg, name, age, alse, phone
umber, GRA), then using the Scanner class can be problematic because thee is
zo simple and elegant way to allow the wee to reeater any one ofthe values after
All 10 input valuce are entered So, instead of using the standard console input
itis a much better user interface to employ a single customized window that,
allows the ser to enter all 10 values. We will lea how to build sch a eas
fomized user interface inthis chapter, As apart of building ofa customized user
interface, we will alo lean how to detect mouse movement and clicking of
mouse buttons,
| program for our own use then we may choose
lenput to enter 10 values. When we writ a prog
ive user interface becomes of paramount por
‘correctness, the user interface of 2 program ofte
forthe users to celect one program aver a
ofthe program to include the user interface that
isually appealing,
‘The typeof user interface we cover inthis chapter is called
(GUM, Tn contrast, the user interface that uses System in and Sytem out
‘exclusively is the called the non-GUI, or console user interface In Tava, GU-based
programs are implemented by using the classes fom the standard javaxsuing and
Java.avn packages, We vill refer to them collectively a8 GUI clarcer Whe We
‘eed to differentiate ther, we will eer to the eases om javax. swing a8
‘and those from java.a a ‘Some of the GUT objects from the
jvaxswing package ae shown i Figure 1.1
Inthe older versions of Tava (before Java 2 SDK 1.2), we bad only AWT
clases o build GUI-based prograts. Many of the AWT classes are now superseded
by thei counterpart Swing clasts (eg, AWT Button classi cuperteded by Swing
‘Button class) AWT clases are sll aveable, but it ie generally preferable to use
Swing classes. There ae two main advantages in using the Swing classes over the
AWT clases,Chapter ctmctomirhegancing 789
sue
Figure 14.1 vesou: Gulobjecs trom the jvaxewing package
First, the Swing classes provide greater compatibility across diferent opr
sting systems. The Swing classes ae implemented fully in Java, and they behave
the same on different operating systems. The AWT classes, on the other hand, are
plemented by using the naive GUL objects. For example, an AWT Button is
‘implemented by wing the Windows bution abject forthe Windows operating)
tem, the Macintosh bution objet for the Mac operating sytem, and s0 forth
Because the behaviers of underlying platform-specfc GUI abject are not neces
sanly identical, an application that uses AWT classes may’ not behave the same 02
the different operating systems. To characterize the difeence in implementation
the Swing classes ae called lightweight classes andthe AWT classes heanyveigh
classe.
‘Second, the Swing classes support many new functionalities not supported by
the AWT counterpas, For example, we ean easily display an image inside a bation
‘in addition toa ext by using + Swing JButton, but ony text can be displayed inside
‘button with an AWT Button
‘We discuss the Swing cates exclusively, We use the AWT cates oaly whea,
there ate no counterpart Swing clases. One thing we must be careful of i using
them ie not to mix the counterpart in the same program because of ter difference
in implementation, For example, we should not mix Swing batons and AWT but
tons or Swing menus aad AWT menus, I an AWT lass has no counterpart Swing
clas, for example, the AWT Graphics class, then using it with other Swing classes
poses no problem
ee
weight clases A a general ule because they are implemented iferen
ee a eee eee
sve
Many AWT asses ae superseded by the Swing counterpart clases but they are
stil avaiable inthe newer version of Java SDK Why? For example if the Sying
Button chssis a better version ofthe AWT Button class. then why dont we get
‘ofthe Button cass? The first reason isthe bacrd compatiity, which means
programs wt for alder Java SDK ll continue to run under neve SOK Had a
‘newer Java SDK dropped the superceded AWT clases, then old programs that use
those AWT dasses would not run under the newer version of Java. The second
reason isthe availabilty of compatible Java interpreters When you write pro
‘fam sing Swing clases, then the users of your program musthave a compatible
ava interpreter installed on ther machines your users employ Java interpreter
‘that recognizes only ANT classes, then you have no option but to wrt the pro
‘fam wing only the AWT classes.
‘To uid an etfecive graphical user interface using objects rom the java swing
and ova awe packages, we must lea a new syle of program conzol called en
Given grosrinmins Aa event oocute when the user interacts wath GUI object.
For example, when you mov the cursor, click on abuton or select amen choice.
‘an even curs. In event-driven programs, we program objects to respond to these
vents BY detining eventhanding methods. In this chaper we wil lean the
Tandamentas of eventasiven programming
‘Since the main objective for this chapter isteach the fundamentals of GUL
and event-driven programming abd not to provide an exhaustive coverage ofthe
‘Swing classes, we wil cover only the most consmon GUI objects
14.1| Simple GUI{/0 with JOptionPane
(One of the easiest ways to provide asimmple GULbased input and output it by sing
the JOptionPane clas. For example, when we execute the statement
Joptiontane.showteseageDialeg nui," Love vaya")
the dalog shown in Figte 14.2 appears onthe center ofthe screen
In 4 GUI envionment, there ae basically two types of windows: a general-
‘purpose frame an special purpose dialog I Jaa, we ute a JFrame object for
4 frame window and a JDialog object for @ dialog, The Sex argument t the
ShowNessageDialog method isa fame object that contols this dialog, ad the
Sccond argumest i te text to display. In the example statement, we pass aul
reserved word, meaning thece i no frame object If we pass null a he fist eu
rent the dalogappedzs onthe center of the ceson. L we pas a eae objet thenSince opbetany 79%
igure 14.2 A simplemessage dag created by the showMessageDalog ethod by wing the
3OptionPane cs.
the dialog is positioned at he centr ofthe fame, Rus the Ch1@showMessageDia
Jog elas and conten this bebavin
hrashowmessageDialeg
ee
chidsnowtessageDiatog ¢
public static void main(Steisatl
jFrane.setsize (400,300)
jerome cetvsatble (ez)
optionPene.showwescayeDialog(jfrare, "low ace you?")y
JOptienPace.showessageDiales null, "Good Bye":
[Notice that we ae not creating an instance of he Jal clas directly by ou
selves. However, whe We cll te showfessageD alog method, the JOptionPane
‘lassi actualy creating an instance of JDalog internally. Notice that shower
sageDialog isacass method, and therefore we are not reaingaJOptonPane abject.
we need amore comple dialog then We create an instanes of JDialeg. But fora
simple display of ext calling the showMessageDlalg class method of JOptonPane
‘would suthce.
we want to display multiple lines of text, we can use a special character
sequence Wt separate the ines, 20
soptiontane.showteseageDiateg (nuit, *one\ntvo\nchree"hs
‘which will result in a dialog showa in Figure 14.3
‘We can also use the JOptionPane class for input by using its showlnputDialog
method, For example. when we execute
the dalog shown in Figute 4. appears onthe sereen To assign the name input to
‘a input sting, we write
Sepst = dopesonPane. showinpstbielog(null, "Enter cext7
Unlike the Scanner class that supports diferent input methods for specific
ata types, thats, nestnt and nextOouble, the JOption?ane support only 4 sing
Figure 14.4 aninputdalog that poets as ltt cllg the showlnputDalog cs rethod ofthe
OptionPane css wth What sour neers the methoessecend aguentChase Method Example
Tategee [| pareetat | toteger.pareeint ("25") = 25
bosbie | persedoubie| oosnie.pazzevounie("254) > 25.9
Double parseDoubie ("abs") —> error
Ipat. To input a numerical value, we need vo perform the sing conversion our
selves. To inpat an integer Vale, sy, age, we can Wie the code as follows:
soptiont ane. showiaputDialeg mull,"
ane age = Tncegee pacaernt (ete)
the use ener a sing that cannot be converted to a int, for example, 1234 oF
abct25.« Numberformatéxception enor wil sult. We use conesponding Wrapper
‘lasses o conver the string input o other numerical data vals.
"Table 1.1 ists common wrapper classes and their corresponding conversion
methods.
2. Using JOptionPane input dialog, wate a saterent to inp the person's st
5. Using JOptonPane input dialog, write a statement to input the person's age
inte
14.2 | Customizing Frame Windows
To create customized user interface, we often define a subetass of the Frame clas,
The helper cast MainWindow we used in the Sample Development section of
Chapter 13. for example, sa subclass ofthe Jrame class. The JFrame cass contains
the most rudimentary functionalities to support features found in any frame Win
dow, such as minimizing the window: moving the window, and resizing the window.
{mn wring practical programs, we normally donot create an instance ofthe JFrame
class because a frame object is not capable of doing anything meaningful. For
‘example, fe want fo we frame window fora word processor, we needa frame
‘window capable of allowing the ueet to enter, cit and paste text; change fon
rn ex: and so fori, To design such frame window, we would define a subclass
[ofthe JFrame class and add methods and data members to implement the needed
functionals.
‘Before we show simple subclasses of ram, e's fist look atthe following
program which displays a default Frame objec on he seren:
ee
public static void main(sering{l seseh (
‘When this program is executed, a default Jrame objec, town in Figure 145,
appears on the sreen Since no methods (othe than stile) to the properis
Of the JFrame object such a its tle, location, and size) are called, avery sal
‘ofall JFrame object appears a the top let comer ofthe sexe,
ttc asso et
Figure 14.5 &deauk Frame window appears atthe tp ef comer ofthe ree[Now lets deine subclass ofthe JFrame clas and add some default charac
terns. To define «subclass of another class, we declare the subclass withthe
‘eende reserved word ovens So, to deine a class named Chiaramesubelasst asa sub
‘last of JFrame, we declare the subelas a2
For the Ch14ramesulbcaet clase, we wil add the following default charac
1+ The leis se to My Fist Subclass.
+ The program terminates when the Close box i licked!
+ The sizeof the frame ist fo 300 pines wide and 200 pines high
+ The fame is positioned at sereen coordinate (150,250),
‘The effect of these properties isilustated in Figure 14.6
‘All hese properties are St inside the default constructor. To se the frame's
tte, we pas the ite othe serie method. To set the frame's size, we pass its wach
and beigh to the setsize method. To position the ram's top lt corner fo the coor
nal (x), We pass the valet xand yt he setLocaton method. Finally, o terminate
omy, =
130250)
——
Figure 18.6 How annonce of Ch14iFrameSublestwillappearon the cee
“We dn sci wind wl cv bt pon des ine. ea
seca el ern epg yi he nd aso hh ee
‘egos Wnts pln
the program when the frame is cloted, we cll the setDetaucloseOperation with
the clas constant EXIT_ON_CLOSE as an argument The Chiframesubclass classi
eclred a follows
a
$e fined ine FRIMER_OAICIN = 150;
public chi4sFranesubelass? () (
Hane one Ceame detauit propercion
setricle (ty First subelass") Cal iaibarnt
setsize (FRAME IDI, FRAME RETCAT) oy
Entiocstion (GRAMELX_OAIGIM, HOGI ORIGIN);
selberaultClovedperat ion ( PRIT_OLEIOSE 1 -
[Notice the methods suchas eile, setSze, and others ar ll defined inthe JFrame
ands ancestor clases (ancestors are the superclasses inthe inheritance hierarchy)
[very method of a superclass is merited by ts subclas. Because the subelass-
supetelas relationships are fone into aa inheritance hierarchy, a subclass inhents
all methods defined in it ancestor claviesAnd we can eal a iaheied method
Troms the method of 2 subelass in the manner idenea to ealing a method dened
inthe subelas, hat is, without using dot notation o by using dot notation wi the
reserved word thi
ere
pepsnenle pie otoconia SHHeres the min last test the CntsFramesubclst clas:
De
public static void maiz(steing{l arse) (
hnyFeate ~ new Ch14JFranebubeLa‘e1 (07
rnyPeane.setviesbie(txved
When itis executed, an instanceof Cht@FrameSubclasst appears onthe seeea. as
slustrated in Figure 146, Notice this main clas it denial to Ch€Defaulrame
tencept for the creation of a ChiAlframesubclss instance instead ofa Frame in
‘ance. Also notice that there's no need to import the javex. swing package because
the main class doesnot make any dtet reference to the clases inthis package
Since we dd not set the background color for Ch14/FrameSublasst, the default
white was used asthe frame's background color. ote" If you see diferent
buackazound color, sich as gray. then mos likely you are using an older verionof|
Java, SDK 1 orcalier) Let define another sbelas named Chi@frameSubelss2
that has a bie background color instead. We will define thi lass a¥ an istanable
tain class 40 we dont have to define a separate rain cat, To make the baccround
‘ententpane _appearin blue, we need to acess the content pane ofa rame. A Teame’s cone pane
designates the aea ofthe frame that excludes the ile and menu bars an the bordet.
isthe area we ean se (0 display the contet (text, image ec). We access the
conteat pane ofa frame by ealing the frame's getContentPare method. And (0
change the background color to blue, we call the contest pane’ssetBackground
rethod. We cary out these operations in the private changeBkCalor method of|
(Crtdiramesubelae?. Here's the class definition
ee
copter
public atatie void nain(seeingt] arse) (
ChiasPraneSubelase2 frame = new Ch149Franassbels#e2 0)
frine.cetvsasble (esse)
public eb14uFranesupeteee2 0) ¢
setTitle ("Blue Background JFrame Subelase")
Setsize —(GHaMEL SIDI, Fea eT
setiecstion (Fh
Seep oarenh PARI ORIEN)
ersesont
ILNeLOBED
changetncetor
conenteane. cetbackyzound (Color BLIE})
Running the program will result in the frame shown in Figue 14.7
appearing onthe eteen, Notice that we declare the variable contentPane inthe
‘hangeBkCalr method st Container We do not havea class named ContentPane
By declating the variable contentPane a8 Container, we can make i sefert0 ay
instance ofthe Container clase or the descendant classes of Container, This males
‘ourcode more general because we ae not yng the variable contetPane any one
Speatc class. By default, the getCortertPane method of JFrame infact returs the
escendant class of Container called JPanel, We wll describe the JPanel clase in
Section 18Figure 14:7 An instance of ChtaiFrameSubdase tht has blue bucground
14.3 | GUL Programming Basics
In this setion, we will develo a sample frame window that illustrates the funda:
rentals of GUI programming. The sample frame window bas two butions labeled
{CANCEL and OK When you cick the CANCEL button, the window il is changed
to You diked CANCEL Likewise, when you click the OX button, the window's ue
|s changed to You ceked OK. Figure 148 shows the window when iis fst opened
snd after the CANCEL button cick,
“There are vo key aspects involved in GUI programming, One isthe pace
iment of GUI objets o the content pane of a frame, andthe ober isthe handling of
vents generated by these GUT objets, We will develop the sample program in 0
‘eps. Fist we wll define a JFrame subelats called Cht@)ButtonFrame to show how
the two butns labeled OK and CANCEL ate placed onthe fame. Then we wil i
plement another subclass called chtaButtonevents to show how the button events
fae processed to change the fame ie
Button Placement
protbusen The (pe ofbuton we use here i called a pushavion, Since we discuss the push
buttons nly inthis chapter, we will simply cll thems buttons. Toute a button i a
progtam, We cea an instance ofthe jaaxsing JButton clas. We wil cate tW0
ce
igure 14.8 A sample window when iis fst pened andatethe ANGEL buon clicked
‘buttons and place them on the frame's content pane inthe constructor Let's name
‘he two butonscanclButton and okBurton, We declare and crete these buttons in
the following manne:
‘The text we pass othe constructors the label of a button After the batons ae ere
aed, we must place them on te fae's content pane
‘There are two general approiches Io placing baton (and other types of CUL
objects) on frame's content pane, one that uses a layout manager and another that
ay oes nt The iy! nansrer fora container isa object tha contol the placement
rut of the GUI objects. For example, th simplest layout manager called FlwLayout
places GUT objects inthe tope-bttom,leftonght order If We do not use a lay
‘ut manager, then We place GUT objects by explicly specifying ther position and
stiatte Size on the content pane. We call this approuch soe positon ns In this section.
Pritenng we will use Flowtayout. We will discuss other common layout manages and
absolute positioning in Section 14.4.
‘To te the flow layout, we ste layout manager a frame's conent pane by
passing am instance of Flowayout to the setLayout method
(raw Floetayout 11
After the layout managers st, we add the two buttons tothe content pane so they
‘become visible when the frase is displayed on the cree:
content ane ad foktut ton)
content Pane. aalfeanee Button)
[Notice thatthe sizes ofthe OK and CANCEL buttons at different, The de-
fault sie of a button depends onthe numberof character inthe butons label. We
‘an oveide the default by calling the setS2e method. For example, we can sel thei
‘wid to 80 pines and height to 30 pixels by wating
ohbstten.settize(20, 30);
Sanceiaicton .eetsize (RO, 30);
However, the stsize method doesnot ake effect when the layout manager is wed,
only works with absolute positioning. We won'tbe using the setSize metho here
"We are now ceady forthe complete isting ofthe Ch14JButtonFrame clas
eesis serene (
public static void main(stringt) args) (
Ae chiarosesenteare () (
Container eostenteane = getconteateane( 1:
pecsize (PRAM SH97H, FRAMESESCHT)
sable sole)
Je (serogran chi dvsuctent sane"):
SesLocstion (PRAM XOORIGIN, FRAME Y_ORTEIN 7
ccontenttane.secLayeat (new Ploxtayent 014
Gkbuteon = new Jbuttor (3k) y
consent ace. ddoebutton)
sttutton = new J0steon (MEANESL")
(enthase-add(easeelsutton) +
operat 408 (EXTON
‘Wher we run the program, we se two butons appear on the frame, We ca click
the butons. bat nothing happens, of course, because the code to handle the button
clicks i ot yet added tothe cats We'll add the required code next,
e
Handling Button Events
[Now e's stady how we proces the bution clicks. Am aeton such as clicking abst
{ome called an «and the mechanivr to process the events event handling The
‘eventsbandlng model of Tava js based onthe coneepthown as heron Hare
vent model. With this model, event handling is implemented by two types of
‘objects event source objects and even lstence objects.
‘AGGUL objec, sich ae a button, where the event occurs is called an event, ot
simply the ensure. We say an event source generates event, So, for example,
‘when the user clicks ona bution, the corresponding /Buton object wil generate 20
‘ction event When an event ie generale, the system notes the relevant event ls
{ener objects, An event lislener objet, ot trply ane lvvonr, sam object tha
includes metho that gets execute in response to generated evens Its posible
Tor a single object tobe both an event source and an event steer
‘Among the many different ypes of events, the most common one is called an
ton even For example, When a button is licked or a menuitem is selected, aa
‘vent source will generate an action event, Forte generated events tobe processed
‘we must associate, oF reise, eveat listeners to the event soures. Ifthe event
“ources have o registered listeners, then generated event are smply ignored (his
is what happened inthe Cht4lButtonframe program), For each typeof eve, We
have a corresponding listener, For example, we have action listeners for action
vents, window Isteners for window evens, mous listeners for mouse evens, and
So forth, Event types other than action events are dscusted ater in this chapter IE
‘We Wish to process the ection evens geaerated bya button, thea We must associate
{3 action listener othe baton.
‘An object tha canbe regisered as an aeion listener must be an iastance of «
lass that is declared specially forthe purpose. We eall such class an action li
leer clas. Fortis sample rogram, lets name the action listener class Button
Nandler, We will desribe how to define the ButtonHander clase shortly, But fst
‘we will show the step to register an instanceof gutonMandler a he ation listener
ofthe two action event soureesok@utton and cancelButton-—of the sample ame
‘window
“An ation listener i associated to an ation event source by calling the event
source's addActontstener method with thi action listener as argument For x=
nile, io rogister an instance of Buttonitander at an action lisence of okButton
land cancelButton, we can exceue the following code
bottoniandiee handler = new Buttentiandler 7
oxnurton.adaner onistener (handler:
Notice that we ate associating a single ButtonHandler object as an action
listener ofboth buttons, because, although we can, iti not necessary to associate
‘wo separate listeners one forthe OX bation and anther fr the CANCEL bation. A
single steer canbe associated to multiple event soures. Likewise, although no
Irequentiy uted, multiple listeners can be associated to a ving event soure,[When an event source generates an event, the system check for matching
registered listeners (efor action events the system looks for eegstered action
steers, for window events the system looks for registred window listeners, and
so forth) If there is no matching listener, the event is gnored If there i amatching
listener. the system notes the listener by calling the listener's coresponding
method. In cate of ston events, this method is actionPerformed To ener that the
programmer includes the necessary actionPerformed method in he action listenet
lass, the clase must implement the Aconlistener interface. The Butondander
las, fr example, must be dined in the following ay
clase buttontindier inplenents Aetionkistenes (
,
‘Remember tha, unlike a elas, aJava interface includes only constants and
slptrac methods. The java. awtevenLAeionistener for instance, is deine as
red{hetiontvent eve}
‘The Buttontandler cla is defined a follows:
class puttortiandier implements hettonttatener (
public void cettonterfocrad(etenbvent eve) (
‘An argument tothe actlonPerformed method is an AcionEvent objec that repre
Sets an action event, andthe AclonEvent class includes methods to access the
properties ofa generated event.
"We wan! o change the lite of frame to You cked OK or You ced CANCEL.
depending on which button is clicked. This i done inside the actionPerformed
‘method. The genetal dea ofthe method i sfllows:
public void actionterformed{nctionivent eve) (
,
rite (tau clicked * + buttentext)
“The fe statement setreves the text ofthe event soure the text of the okButton
the sting OK and the text ofthe canclButton ithe sting CANCEL), We ean do thi
in wo ways, Te first way isto use the getActionCommand method ofthe action
event object evt. Using this method, we can evieve the texto the clicked buon as
\e-tonconnsna()?
‘The second way isto we the getSource method ofthe action event object ev.
‘Using this method, we ean etreve the text of the clicked button as
Jpstton eltexeamurten = (seston) evt.getsouree ()
Hering. autores = lickeabutean gettext (17
[Notice the typocasting of an object returned by the getSource method to JButton,
‘The object returned by the getSeurce method can beam instance of ay clas. so We
reed to typecast the returned object toa proper class in order to se the deszed
ethos
"Now to ind the fame that contains the event souee, we proceed in two steps
Fist, we get the 10t pane to which this event source belongs. Second, we ge the
{fame that contains this root pan. Here's the necessary sequence of statement (0
access he frame that contains the event souree
oRootane soatPane ~ eliekeaiutton.getReetPane( )
Frene frame” = (UPrane) rov.eere,getbarent (1
‘A frame window contains nested layers of panes (the content pane in which we
place GUT objec is one of them). The topmost pane is called the voor pane (2
Instance of RootPane). We ean acess the rot ane of a rame by calling the GUT
object's getReotPare method, Prom the root pane. we can acces the frame object
by calling the root pane's getParent method, Because «root pane can be contained
by diferent ypes of containers Urames, dialog, ete), we need to typecast the re=
‘tuned objet to JFrame in this example12 cuneyemmagtnis 805
Heres the complete Buttontiandler clas:
OV _—
snport qavax.ewing.
clase buttonlondier (aplenents Aetioniteteres (
pubic sucteniendter() (
,
public void setsontertorned(Retfontvent avert) (
sacteen eliexeaautean ~ (JButter) evert.getsousce (1?
dacottane rootPane ~ elickedbutton.getkost?ane()z
Feane Stare > (JPrare) roetFase-geczeren (0;
String puttonText ~ eliekedButton.get Text (15
teane.setTitie(*¥eu etieked * + buttentexths
[And here's the complete Ch14/ButtonEventsclise (notice that tis clase ie
cssenially te same asthe 1 VButtonframe class excep forthe portion tat dele
‘vith the rgiszstion ofa ButonFandle to two eveat sources)
DP
. a a. gava
SSport evan?
public static void main(scringt) args) (
chisshuttontversa frase new chi scButtentvente ()s
frase. setiable (true)
,
public eh14utectonventet) (
containe: contentFane = getcontentzane( 1
Hane ene tesa properties
sotsine(pRaMR.A°DTH, FRRME_ARTET)
Sethestsable (easel
pernstie ("bso9
petiocstion (URit
jspsetontsane')
ORIGIN FRAY ORIEIND 7
costentPane, set Layout (new Plowayeut (0)
HHexeave aoa place te buttons on the feane's content pane
oenutton — new Jaueton (ec);
contentPane: saa (akbsttan
carcelbutton = naw JButcon (*EANCELN
contentfare. ede (ccnee=aut ion);
oosetecing nlandler a# an action Listener of the
Canceltutton audacslenttorenes (andere)
Sebutron.saaicrsoniistenes (handles):
setbefeuleClosedperst ion (EXIT ORELOSE);
‘Making a Frame the Event Listener
Instead of erating a separate event listener las such as ButtonHanaler, is act
ally more common oe frame be the event listener ofthe GUT abject it coniains
‘We stated earlier that any clas ean implement the ActionListener interface. We ea
declare a subclass of Jame that implements the ActionListener interface. As ah
Iuseation of this technique, les define a subclass of JFrame called Ch14iButon
Frametiandler. This cast combines the functionalities of the Chi@Buttonévent
sand BurtonHandlr clases,Heres the clas:
tmport javan.eving.*;
public static void main(steingt] ase) {
frame. s6¢VLaible (eeve)
public chicspstconteanetardies() (
fer contentPane = getcontentPanet 12
secSiae (PRAME_W9TH, FRAME AEIGHTD:
detherleable eaten)
sethecation (FRAME ORIGIN, FRAME Y
fkbutten = naw Jbucten 0K)
contentPare.saa(okbuteon)
ccontentPane add esreelouteor)
‘caneetbutton,addhct Lent iatener ental
‘oksutcon. addict tonListene: (this)
Thaw ChIAvBUC Eon rantlandine (7
208 chapter
petbessulCloseogerst on (E11i_08_¢L05E)
,
public void sccionPerformed{netionevent event) (
Geutvon cliekeahurton = (JRuvten) everr gecsoureet)s
settitle(*You clicked " + buttontext); 200,
a ihe Fnawa_tcontenn = 238)
public chidFlowayoutsenpie() (
SetSiee (GRa¥S NIDTH, FRAMEAEIGHTY
eritle (rrrogram chistlewsayoutsanpie™):
Figure 14.12 Picenent of ve butlons by ing FewLayout when te rameis fst opened and after the
amersresaed contenttane ~ getcontenttane( 2
concentPare. cetbaceqeoua (cole WIDTE)
contentPane. set Leyost (new Flowayout())
[Notice the default is center ligament We ean change itt eft or right align Joseate au piace four 6
content Pane. set ayout (new FlowLayout (FLew.ayout LEFT) Butcons = new sostten ("es
Duttont = new Jnstton (tbs
& buttons = new Jbstton (tbs
contentare. set Layout (naw FlovLayout (PLowayout RIG): content ane, adatbuttonl)
contentPane.aadnittond) 5
er's the complete sample code on taste on)
con aa(outtont)
rs sorseenenee eee)
chapter 14 sample rLiueteates the use of Flowtayeut setbefauleeloseoperst on EXITOS CLOSE); -
,
File: chcrlowieyoutsarple jaye ;
import Javasautsyi | Ei
tn a
ene es |
a uae on ‘soma
Figure 14.13 Pacenen
rameleresaed
ve batons by wing BorderLayeut when the ome sist opened and aierthe
c ‘The second layout manager i jos. ow SorderLeyout This layout manage di
ides the container int ive regions: ceater, nor, south cas, abd west Figure 14.13
shows ive buttons placedin thse five regions. Th sight rame in he igure isthe state
fteritisresiaed. The north and south regions expand o shrinkin height only. he cas
fand west regions expand or shrink in woth only, and te enter region expands or
Shrinks on both height and width. Not al egions have tobe occupied. Figure 14.14
‘hows the frame with oly the center and eat regions occupied with batons
‘We se the dorderLayout analogously 28
contenteane,setlayout (new Bocdesiayout 1%
and then we place the GUI componeats. in his cas, buttons wih the second arg:
rent specifying the region,
content Pane. saa (a:ttonl, order
content? are. sea (astten2, aeraeruayeus £0074):
contertPare.caa (austen, eraertayous EAS")
conterteane. eda (buttond, ordertayous NES?) +
contenteane. cua (buttons, SoraerLayour CENTER) ¢
fact NORTH
‘The Bordertayout used in Figures 14.13 and 14.14 has no gaps between the
regions, which she default. We can specify the amount of vertical and horizontal
gaps between the region in pnels. For example, to eave L0-pixel-wide gaps and
Dovpiel-igh gaps between the regions, we eeale « Border.ajaut objec BY pats
ing these value a arguments to the constuctr,
costertPane.cetLayout (new Bordecteyout (19, 20117
jure 14.14 Placerent of twobotons by asin
ceutiesions
Here's the complete sample program:
import java-ave.
Ae fined ine FRAMER_ORIGIN = 280;
public acetic void main(scring() aese) (
Magedeciayoutsangle rane ~ nev ShidordecLayastsanpie():
Srane.cetVieible(ersel
,
public chisBordertayeutsanple() (
Container content Fane,
see (ERAME RIDES, FRAME HEYGHT);
petite (*Sroqrn Enidierdestayoustanpie')¢
SeLLocat ion #Ai¥_JORICIN, FRAME! ORIEIN |contentPane ~ getcontens#ane( )
content Pane. sesuacrgeaund (Color W:IE)
contentbare.sesLavect (new Borsertayact (1);
Soteant = new Jautten (1
Boteand = new opoteon(
buttons © new dhutten "button
ccontentPase.ads(autten’, Borde:Tayest NORTH:
contentPare saa (outtenz, Bocdestayast SOUTH;
contentPare sas (autters, Rordestayest 7ST)
contentPane add (butters, Bordeciayos CENTER);
setbecsultcloceoperstion( EXIT_ON LOS 17
aT ‘The third layout manager i avs sve Gi ayout This layout manage places
Gu components on equal-sizeN x M grids. Figure 14.15 shows ive buttons placed
fon 2 X 3 gids. Components are placed in top-c-botom, eftioright order. The
fume on the right in Figure 14.15 isthe stat after its resized Notice the numberof
rovts and columns remains the same, but the wid and height of each region are
changed
"To create a Griayout object, we pass two arguments numberof rows and
umber of columns.
contentPane.cetayout (new Seidiayeut (2, 3)11
We then place GUT components in the manner analogous to the one wsed for
FlowLayout If he value provided for the numberof rows is nonzero, thea the value
sve speciy forthe numberof columns is stall ieelevant. The layout wil erate
the designated numberof rows and adjust the numberof columns so tha all coms
ponents wil ft inthe designated number of ws. For example placing the ve Bu
tons with any one ofthe following tte statements will sult isthe same layout
namely vo rows of gids:
costentPane.cetoyout (new Seidbayeut (2, 9))7
contertPane.cetieyout (new Seihayost (2, 19)
contesteane.cetLayeut (new Geithayout (2, 5)17
226 chapters cn
we
women
Figure 14.15 Pacementof fv buttons by sing Geyout ow ows and ve olonns whe the
framels tic opened and ater he tome vse
‘ere's the complete program isting for nt 4GriaLayoutSample
——_—— eee
smpost javax suing.
impose java sve +
clase chitcrictayoutsanple extends Jrane (
Steeie Gina int PRAMEAPTGHT. = 200
aad ine FAME _ORIGIN = 2504
public static void nain(serinat] acael (
cnscriazayoutsampie fran ~ pew ChlGriazayoutsanpie()?
feane,eetVisible tessa)public chisseisiayoutsample() 4
poston
setSize — (PRAME_WIDTS, PRAMG_HEIGHT) ;
Sterifle Grrosran chissrlarayeursonpie*)
setlaeat ion (FRAM_XORICIN, FRANE SORTS)
contentPare ~ getcontentPane( 1
contentPane.secusckground( fol0e ALTE}
contentbare.sesLayeut (new Geiaayout (2.3))7
button = new dputvon(*bscton 3°77
botton? © new Rotten (button 2°14
bbuttong = new JButten(*bstten §*))
bboreans = new screen oH
contentbase ads (buttons)
ccontentPane. ada {bitter}
content Pane. sde (Butter)
Conventtave aad (watery
Scntentpave.aaa (butters
setbeesustCloceoperstion{ EXIT 08 LOSE 17
is posible not to use any layout manager IF we do not use one, then we
place GUT objects cn the frame's content pane by explicily specifying their po
tian and sie, Weeall his approach shoe poitnn. ARotgh ayout mansgers
fe very useful in practical applications, knowing various layout managers isnot
indspencabic for leaning object-oriented and event-driven programming. So using
sbroite portioning is accepable wile learning object-oriented and event-driven
programming. Keepin mind. however, tha o bull practical GUI-based Java pro
rtm, we mast learn how to ue layout managers etlectively
“To use absolute positioning, we st the layout manager of frame content
ane to none by passing nul othe setLayout method
content Pane. cetayout (221) 5
‘ter the layout manager is eo null, we place two button atthe position and in|
the size we want by calling the butlon'ssetBounds method asin
oxsurton,catounds (75, 128, #0, 3907
as chapeau
Figure 14.16 ths dagram tasvates te process of eeaing abutonandplachg on fame
‘where che fst two arguments specify the position of the button andthe last wo
arguments specify the wid and height ofthe button. Finally to make a buton ap
pear onthe frame, we need toa itt the content pane by calling the a method
For example, to add okButton, we call
content ase. ade fok@urton
Figure 14.16 illustrates the proces
“Here's the program listing for Ch14AbsolutePostoning:
smport Javan.suing.*s
Smport javaave
class chicabsoiuterecitioning extends JFeane (
private static final ine FRAMLHIDTE = 300;
Private static finel ine SRAMEjBicHD = 220;
fined Ane FAAKEX_OMICIN = 250public static veid main(string{) segs) (
‘Scone. setVistbie (ue) “
loeolutetosistoning
,
public chistbsotuteresitioning() 4
Container contentPane = getcontentPane()
bottle (PRQME WA9%H, FRAME ABECHE)
setteoizable false);
seutiete (00 es"
Settecat ion (FRAME ALORTGrN,, PRAME_ILORTONM |
okbutton = new JBsteon (%0%");
Skoatconcec Bounds (70, 125, GUTIONMIDTE, 6T
Contenttare.ada(okzotton)
contensfsne sas (esncel outer) a “_
oNLeLo8e)?
2 Which layout manage divides the container into gis of equal size?
13. Wate statement 0 eeate a oeder Layout with 20.piael gaps is bath
orzo and vertical iectons
146 | Effective Use of Nested Panels
Inthe section, we wil discuss how to nest panel effectively to get a sized layout
‘of GUT components Itis posible, ba vr) dfcat, to pate all GUT components
‘on a single JPanel ot other types of containers. beter approach i to use multiple
panels, placing panels inside oer panels. To luswate this technique, we Wil
cate (Wo sample frames that cootan nested panes. The fst semple, shown in
Figure 14.17, provides the user interface for playing Tic Tee Toe. And the second
sample, shown in Figuze 14.18, provides the user interface fr playing HiLo. Note
{hat we only strate the visual ayout using nested panes. The sample frames 60
rot inelude any code for actually playing the games
‘The frame shown in Figure 14.17 has four panels, The topmost JPanel, the
content pane ofthe fame, hata border layout. The eoatent panes centr segin is
Figure 14.17 A sample ame thet contains neve pane: Four Panel objet ae uedin ti Fame
Figure 14.18 another sample fame that contains nested panel Five Panel objets ae used nts ameaerial comaae
Figure 14.19 Th dagrem shows how the panel ofthe Fame in Pigure 1417 ar nested There re
to storePanl. The gamePancl iss speclzed JPanel tsa acs 9 Pane) na wrt» tid yout
sceupied by an instance of Cht4TcTacTosPanel named gamePancl. ChY4TiCTa
SoePanel ise a nested panel We wil design and implement his panel athe end
ofthis seetion, The content pane’s est epion i occupied by an instance of anther
Janel named controlanel A border layout is used for this panel. The north region
of controlParel is occupied by another JPanel named scorePanel, and the south
tions ocupied by a JAutton Te layout for sorePanel is set oa gr layout with
four grids, cach occupied by a JLabel object, The nesting relationship is shown in|
Figue 16 10
"When we nest panels it soften very useful to matk thet borders. In this san
ple frame, we use 4 tiled border for scorePanel and a lowered bevel border for
famePanel A tled border draws a rectangle around the panel and displays «desig
ated ie We erat e ie border by ealing the class method createTitledSorder
ofthe Borderractry clas and assign to panel by calling the setBorder method
Here's the statement:
DerderPactory .exeateTstiedberdes(*Seores:"))
A owsted bevel border gives an illusion ofthe pane! being recessed into the
‘eame Here's the satmnet to erete and st the lowered bevel borer to garePen
gorePenel -cetborder {
vevetsozde=())
‘Additona types of borers, such as line border, mate border, and raised bevel bor-
Ger, are avalale. For mote information, please coasul the documentation fr the
BorderFacory clas.
Here's the complet isting ofthe
public static void main(steingt] arse) (
ChisiectedPanell trave new Chi sestedPane2e1 4
franessetviastle (taal
poblic chldiesreaPanelel() (
Jeet che trae properties
detrscle _ (*erogron cnlchestearanelt");
on (uaa X_ORIGIN, FRAME
costentPane = getcontenteane( 17
ContentPane.setLayout (new Borderlayout (10, 0144
new chisrieracteeranei ()
{atePane| set Sarder (bordertactory -createtowereaeve Border ()))
corceaiPanel setayas: (new Sordertayast( ))7
costentPane.eda(gane?anel, BorderLayat CENTER)
contentPane. cae (contsolFanel, BozderLayout E835)
scorePanel = new JPanel ():
eratanel se: Forder (BerderPaecery ,ereateTitteaBecde: (*3e0r085")scorebanel set Layost (new Griaiayaut (2, 291
Eeosebanel add (ew babel (layer 22°))5
Seorevarel aad (new Jlabel(" 0);
Seorecanel add (new babel ("Payee 2:"))7
SeotePanelsaddtnee Seabel (OF)
contrelPanel vadd (new Jautton(*New Gane"), Rorder“ayout -SOUTH) :
[Remember that this class illustrates only dhe visual aspect ofthe program.
‘There sno code for handing eveats or actualy playing the game
"Now le's move onto the second sample fame. Fortis (rame, we will use
nested panels shown in Figo 14.20, Notice the pane! that has a Border ayout. This
Panel seem extra, but without i the butens will appear away’ from the botlom,
‘loser tothe response label, We feel itis more appealing visually when the buttons
te placed atthe bottom,
HiLaDialey
tae
Figure 14.20 Thenertes pnelrand aerocatednyout manager for MLabielay.
a4 chaperte a
Here's the Ch14NestedPaneli? class
——_—— eee
class chitvestedtaneie? extends JFrane (
Private static final int FRAMEAEIGRT ~ 270)
Private statie final ine FRAMX_ORIGIN = 350)
public atatic void main(seringt) args) (
ChitiectedPaneleztrave = new chi ciestedane<2 0);
srare.cetvsesble (esse)
,
public chisessedPanete?() (
petsize (FARMS_KIDT, FRAME NEXGHT)»
Setsitie (*orogram enlsNestedPaaels2")7
SatLecst Lon @RA¥S_H ORIGIN, FRAME! ORIGIN);
contentPane = gercontentrane()
contentPane.cetiayout (new Geidtayest (3, 10)
geecetanel = new JPanel):
{uesavanel setboraer (borderlactory .exeateTstiedto:
MoUs Guess")
queesPanet add(quesstntey = new STextFied(10})hinePanel = new 2eane107
SissPane:.cetboede: (Sordert sctory.ccesteritiedbardes ("usr=*))
SinePanes ca (eine = new olabel ("let's fay 513")}7
contzolPacet = new saved (m
bettonFanel — new JPanel (7
bottonfane! aaa{enterten = new JRu¢ton (ENTER)
GurtenPane!vaddfearcelsen = new smuttos (eave) )s
controlPsrei sda lasteonPanel, Porderisyect.S00T8)
Bocdextayout 14
content Pane add guecePane:}
ccontenePare ods (hsrth anel):
contenttane.odsleorteo: Panel)
TieTacToe Pane
As promised, let's design and implement a panel specialized in displaying the Te
‘Tae Toe board of x N= N* cells (defaults 3 X 3= 9 cells) Figure 4.17 shows
this Tie Tac Toe panel placed on a ram. The panel handles the mouse click event,
soevery ime the player clicks onthe el the ec or erossis displayed. However,
this code for handling mouse click events i ony for demonszation, Theres 0
logic of actally playing the game of Tie Tae Toe For instance, when we cick on
the cel that ea has aro or etle, new mack epaees the current one Inthe
real game, this should not happen. The demonstration code simply alteraates be
tweet the cross and circle. When we eck th panel fr the fst time, the eee is
placed, then the cross, then th ele and so fort
iow shall we implement this panel? There ae two approaches. The ist ap
proach isto compute the origin point—the top left corner~—of each cll bared on
the dimension ofthe panel and the numberof eels inthe panel, Waen we know the
‘origin point of acl, then we can draw a eitele o cross By sing he drained
jrawOval methods. Figure 1421 illustrates how tht i done. When a ellis
licked, we get the x aby coordinates of the mouse clic location and determine
in which cell the mouse click event has occutred, Once we know the cll, we use
is origin point to draw a ele or crore atthe comect postion and size. This
{approach fequres a fair amount of coding to determine the cell and the correct
postion o draw ins and eircls. We en avoid all tees computations by wing the
Second approach
“The second approach the one which we will adopt here, wies the nested pan
ls, We will define two classes —ChiaTcTacToeParel and ChtaTicTacToeCel—both
fbclasiesof JPanel A instance of ChiTicTaToePane! wil contain N™intanees
of ChiatictacToeCel, each instance representing a single cell n te Tie Tac Toe
board. A chiavieracToeCel object contins one component, namely, an instanceof
Jiabel, Instead of atest, we assign an image icon to tis JLabel object. We have
ws (C9 ler example 6) = (26/3.21/3)
IN,
Talscd A |]
J,
up) Yam | XX lamas] cal =m
i tO I
ve eke) LH
Figure 14.21 the oparouch not adopted Here Ti approuch set as Sera 1. The paris divided
Inc equlste cel A ciclo css can be dain by wing the rawOvalo deawLinemtbod a the
pein sgh ose rom the origin pe ofthe cl
ttyce image les: the ts one fr the ele, the second forthe ross, andthe lst one
for a blank cll These es are named cscle git, cross. git, and blank i, respee-
tively. All tree images have a transparent background so the background color
fof the ChiericTacToeCelt wil be visible, Notice that these image bles mist be pt
‘nthe same folder av the class Bley ChteTicTacToePaneliis and. CntsTeTac
Toeceticas Intl all elt ae assigned the blak gif image. And we tet a line
‘order foreach el so the boundary lies ate visible. Without such boundary Tne
‘we would’ tbe ale totell how many ces the board hal and where each cell be
land aded. When acelis clicked, Ch14TiTacToePunel wll ttt cose oracle
by calling the cell's setContent method.
‘The clase includes one data member elle location, «Point objec, o record
the cell's poston oa the Tie Tae Toe board. Tis information isnot used inthis ar
ple. We need to process the location information when we develop the complet Tc
“Tae Toe playing program,
‘Hete's the complete listing ofthe Ch14TitacToeCell cla:
ee
smport java.sve.+
sapere rem suing.
public class chidrietactascel! extends oste (
public stetie enum Inage (AIAN, CIRCLE, cROs8)public chistictactoecell() {
‘hea mali)
,
public chiTsetaereecell (Point pe} ¢
Inagezcon initinage = new InageZeon(MeLa0k. 312%);
secLayout (naw BoxdesLayout (1);
‘acugrauna(Colet unite);
secborde: (Bardestscvory creates
content = new JLabel (instimgel
sasieostethy
public Point gerFosteion( ) (
,
public void setcontent (Image image) (
seiten Ginase (
case CIRCLE: content set Zeon (naw Inagezeon (CIREL_IAGE 1289)
case ness: content cetteon (new Inagetecan(CROSS_IMAGE_FTLE))
“The main tasks forthe ChiATiTacToePanel to handle are the layout of NE
ccnvarcracToeCell objects andthe mouse click events, Since the board is divided
ito equal-size cells, the grid layout isthe perfect layout manager to use here. BY
using the grid layout manager, the images will stay a he enter of the celle even
‘when the panel i resized,
ach cell isthe source of mouse events, and the container ofthese cells, that
is, an instance of ChtaTicTacToePanel, is desigaated as the Iistene ofthe mouse
vents. Again, the eveat-banling code for this clas is temporary. We will eta
Image of scitle or «eros to the liked ell, There's ao logic here to actly play
the game, for example, to deerine the winner Here's the complete listing o the
‘ChianicTacToePanel lass:
smport java.ave +
Sport jrvane suing.
public clase chidzieracvacbanel extends cPanel snplenente HauseListener (
public chldticrectoePanel() (
tats:
,
public chigricracree?ane) (in
setLayout (new Grietayout (2ize, 2tze)}7
for (int row = 07 ro¥ < aitey cower) ¢
for (ine coi; col catzey colt) ¢
fo) Soe cis Stieractescel ()
pastel)
ietenee (Enda):
,
public void nouseclickea MouseRvert event) (
caletietacreccell colt = (chiérieracteecell) event getsouree():
se (eizciel ¢
11 setContent (Ch14tieracToeCelt. Image CIRCLE);
‘
‘Sell. eetontert Chl4TieTacToscelt Image. ch
»public void nousetntered (Mousedvent event}
public void nouseanited (Moueenvent event}
public oud nouserreesed (Movsebvent ever)
Publis void nosseteleased (Mosearver® avers}
14,7 | other GUIComponents
We will inuoduce other useful Swing components inthis section Pease kep in
rind that we limit the diseasson othe most basic se ofthese components, They
te acsaly {ar more capable than what we preseot here. However, the materils
presented in his section should be enought let you use them in most common sit
ations and should serve a good sarang point from which you ean explore mere
sdvanced uses of these component on yout oa,
JcheckBox
‘The JButton cass represents a typeof button called a pushbutton. Two ober cons
mon types of buttons are ealled checkbox and radio burtone. We will explain the
‘hecksbox bulls inthis subsection and the rao button in the next subsection,
“The IChedkdox clas it wed to rerctentchecksbox buttons Figure 14.22
shows fame with four eheek-box button and one pushbutton, Check-box buttons
‘ae useful in presenting a collection of binary (jena, tue/falte) options. The fame
shown in Figue 1422 gives the user the option to select the programming lab
"age e o she can program with by clicking onthe appropriate check-box baton,
"We deal with the JCheckBox clase sm.a manner very simular to that forthe
‘button class, To rele a eheckcbor baton wih ext Java, we wile
JeneekBox eoBtn = naw JoheckBox 980")
Figure 14.22 irae with fou checkbox buttons and one pusburon,
0 chapter
‘To check fa check-box buttons selected (ie, has a check mark) or deselected, we
call te Selected method For example,
Af (eaten toseiecredt) (
Seabencgectert 017
) atae ¢
fyaten.eut .printin(*¥eo eanre> pragran in *
“chaen.getsexe 017
,
Sst as witha pushbutton, we can retrieve the text associated to a check-box button
by caling st getText method. We can ute the coresponding retText method (0
change the bston (xt
‘The following Chi&iCheckdosSamplet class displays the fame shown in
Figure 14.22. When the OK pushbutton i elicked, we fespond by opening a mes
sage diol with alist of selected programming languages. Inthe progam, notice
{he ute ofan array of sting btnTextn eating an array of JCheckBox batons. We
can asly list any number of names by simpy including all names when binTet is
initialized. for example
serinst) btetext = (ersuaty
‘There's no need to modly the program code. The ease of achieving this generality
is adiect benefit of using panels and layout managers instead of absolute position
ing. (You sill ean doit. but it would bea lot mor tedious work to code the same
capability with absolute positioning)
‘Here's the elas
import Jave-awe."
Smport javalawe seven.
clase chitstheektoxtanplet extends Frame inplenents Actiontistener (
final ine FaAMEEICRT = 200
fame Ane FARKE_OMCIN = 250private Jcheckton{) ehecken
public static void main (se:
Eeane,eetVisible tual
ast] exseh (
public chtschecksoxsanplet () ¢
Besingt) Btatext = (Vavaty Telen, Ménaliank, Aaa"):
aetSize.(GRAM_KIOTE, PRAOG_AEIGHT)
ExGicle [Hrragram enlaveneeZsansuap let")
detiocstion PRIME H ORIGIN, FROM? ORIGIN
contentPane = getcontent Pane):
Content zane, ve: seerqeouna Colo 8075)
SontentPane.setLayout (new BeedecLayout QD
neckrane: = new cPanel (new Grsaiayest (2,2))
Checkbane! setardes (eeranrfactory -eseateritiedterder(
"ean peogsen In"))7
cnecutox ~ new Schecklee[atatext tengthl?
or (int £ = 0; 4 < checxBox.tengtny L091 1
SheckGoxt!] ~ naw Seheekbon twentene (1007
‘hecktane!-aga(eheokeex (111
fokvane? ~ new Panel (new Fowzayeut (103
oxbutton ~ new JBuscon ("017
ohbut on. edahet ionListenes (this)
SxPsnelsadaorbutten)¢
contentPane.addcheckPanel, Bordertayout CENTER);
content?ane.saa(okPanel, Borderiayout 30078)
cetbefauiteloseoperat ion (BRITON CLE)
,
public vold sctienPerformed{Aetsonzvent evest) ¢
Stringhutfer skill = new stringbutter ("You can program so\n")s
for (ane! 8) 4 < checebor.lensehi 1-4) (
22 chaperte a
Af (cheekton{i} iesetecced (0) (
sels. sepend (enecnbox(s] -gectex:() + "in *)
,
,
JoptsonPane.showMeasageDsaleg thts, akill-vostsing()
Although we did not process them i the Ch14/CheccboxSamplet program, 2
30neckBox object generates action events jus as any other buttons do. So We ea as
“ovale am ation steer to ICheckB0x objects, bu itis no hal common to process
action events generated by ICheckBox objes In adiion, a checkbox objet gene
Iensven ates aother type of event calle em ooh. Av item event generated whe the
Sate (elected o deselected) of a check-box button changes. We ean feiser ai
Stance of a clas that implements the Remstenrinerface as an items hstener of a
sGheckox objec. When an tems events generated is femStatechanged method
‘is called, Inside the method, we can check the state of change by calling the ge
‘Statechange method: Here's a sample temstatechanges method
public void itenscatechangea(itentvent evened (
Af (evant getseatechange() = teentvent.seuscrED) (
Syste out printin(*vas checked she box");
c
‘yoter.out.printin ("ou unchackes the ex")s
de
,
>
Heres the Cnalcheckdoxsample2 class that adds the
to the chtalcheckBoxsample' case
ee
n event handling
smpost javaxeving.
Smpect javalave event.
Benbistenes (M47 ohwcaconpnene 003 2a chapter
300 public void scctonPerformed ct ankvent event) (
ine FRANELONTEMN = 1505 agbutfer sk11 = new Stringhufter ("Yes con prozran Sa\n"hy
private static finel int FRAMELY 250% for (int £ = 0; 4 < checkBon.Lengths G0) (
private ScheckBont] eheckonr A (checktox {1} tsseiecred()) ¢
seset ¢ Selisappena{ensetton{s]gee7ex=() + "\n
ew Chi4scheckBoxsanpie? (13 1
voptontane,snouieszegeDislogithia, skill. cestsiag(h)1
public chisscheckborserpie? ( ,
Connor Er ats public void irenstatechanged(itentvert eves) (
verson okmertons JeheckPox sores = (ceheckBax) avert gersouree ():
Feoiast) btavest = ¢ . ety sassy sveing atstes
Jeet the frome properties S¢ (event gecseacechange() o> Leenivest SELECTED) (
pecsize | (ERAME_KIDTE, PRAME_MEIGHT); Beaten vis selectee
Sectitie (*Hzoazan Chisuthecksoxtanee2")s yee
SetLecat Len (@RAME -0R1GI8, HONK ¥ ORIN) Bate = tie deselectedty
concantPane = gatcontencPanet 1p
content?ane.setLayest (new Bocdectayout (1 ‘eevee svoainnsn ge eae
checkPane! = new cParel (new Grseloyout (9,217
chectd ane: et order (oorderfactory -ereuteritiedorde:(
ean Program To"))s —_—_—_
eneextox = new ScheckRoe[otnTextLensthly
tor (ine L = 9; 1 < checkbox. tengens 1-4) 1 RadioButton
hectbox(s] ~ new Jcheekoe(pentex: (21) “The RadioButton clas is used to represent a type of button clea radio button
shectsned add(eheckiox(s)) Simularto a checkbox buton, you ean select of deselect radio button. Bur unlike
cnecnton{s]saditenLsotene: (the): ‘with acheck-box button, you can only select one ofthe radio buttons that belong to
, {he same group. Figure 1423 shows atrame wit fur eadio Buttons and one pushy
Hereate and placa the of Botton button, We an select exacily one ofthe four radio batons a atime because hey be
oxranel = new spare) (new FLowayout () Iongto the same group. When we see: anew one, then tbe erreaty selected ras
Sttucton = new Jeuston (ror), button will get deselected. Radio buttons ate useful in allowing the use to selet
cxburen.sauicesenissrenes (chia); ‘one from a bit of possible choices. The sample frame in Figure 1.23 allows the
ohfsnel-adaloxbutton) sero select the favorite programming language
‘We can use the RadioButton clas inane an identical manner as tht for
contentPane.odd(checkPanel, SordesLayout .CEMIER) 7 he neon cae ie Meheribex, Mestnenen prooeacs tol con nrear
contenteane,caalokvanel, Boederinyeut -S00™H) par aint may “inb aril vont
Hzegister "Exls upon clesing® as a detauit close operation tea burton group. in dation to adding them toa container. Nosce
aetbersulecloseoperst ion (2X1T_ONChOS ‘of radio buttons to «group i logical operation ‘only one radi buon ia group
, canbe selected at time), andthe addition of radio buttons toa container is 8aFigure 14.23 Aitamewithfowrdiobuttensandone pushbutton
layout operation. Here's a portion that exctes radio buttons and adds them 10 a
gf0up (an instanceof a ButtenGroup) and a container (an instance ofa Janel
SuttonGroup Langiageszoup ~ new futtonszoup( 14
foe (inet = 0) 4 < vaatapetton.iengens 164) 1
radiomicton{i} © new oaadiebuttan (est)
IShguagesroup add {raaioburcents])
pedlobane: add(redsobsttonte])
(Thee dots. represeot a pees of actual code not dei relevant here)
Here's the ChtaiRadioButtonsampe class
——
Inplenents Aettentsatener,
private static final int FRAMEXORIGIN = 1507
copra au
private JRadsoputton(] radiepstters
public static votd main(seringl] sea) (
‘h1sokadiebuttentanple érane ~ Rew ChldRadsobuttoneamrle ts
‘rane. setvisible (erve)
>
public chitmadionsttonsample() ¢
Steingt) —taText = ("Zavar, "Crit, “omalitalk™, "Ada" )
secsse (PRA NOTH, FRANE_AETCETD
fectisle (*hrogran chisunadsaaut=on")
Peciocseon(FR_X ORIGIN, FARNE_©_ORTEIN)
contentPare = geecontent¥ane( 17
contentZare.secbeckyeound(Col0: WHITE) 7
content Pare settayouttnew SorderLayout (017
Fasteranel = new JPane: (new Grtatayaus 110)
Eudiepane! set aoraer BosderPactery ,eseavetitiedtorder(
en
angueyecsoup = new 2uttensroup ():
radlobitten, - new JRadiobucten[btnText length
for (int 1 = 0; 4 ¢ radtoButeon lengthy 444 1
Feaobucten{:) = new otadianscvon(otaTent (41)
Ebdiomacton [a] .adasventstenes (this)
Ineguagecroup ads(raa:abueten(3])
psstorane:ada(raaiabutten(s])
,
cadioBulcon{0} setteleeted(trve); /Jeeieete the Fisst ehoice
fokrane! = new Shane: (new Flowayess (1);
okbattan — new 2buttan ("02")
Skbcrron aauncrionisarenes (the)
okPanelsaa(okasteon);
content are. add leatioPene:, GostesLayout CoNTUA)
content tare. ada(oxPenes, Sorde=tayout 00787
setbetisitcloceopesst ton (eX17_98- L082);public void sctionterfermed(Retiontvent event) (
white averite —— malty ¢
Te lfeasionscvert}-saSetectea) (
avorize = Fadlenutten{} gettext
tioaPane.shovlesssqeDialog(thie, "Your favorite Language is *
W eaverive)
public void scenstatechanged {stensvent event) (
onaaievutton couse ~ (UAsdioustten} event getsouece(:
64 (event getscatecharge() == Teensvent SE28CT89) (
JoptionPase.showessageDileg(this, ‘aediodutton 1 +
sourcengettext() +
eT ace
Everytime a radio button ie selested, the RemStatechanged method scaled
lovie, Te fr time forthe deseletion ofthe eurenily selected item, andthe see
fond t forthe selection of he new item. Alto notes the alement
adsoperton{0} -20t selected (teva
in the constructor. I we doa't include this statement, then no items wil be selected
‘when the ieme is st opened. For radio buttons it is more common to stat With
fone preselected when they first appear on the screen,
3ComboBox
‘The JCombotox clas presents a combo bor This lassi similaro the RadioButton
lass inthaticalso allows teaser to slectone tem from alist of posible choices The
268 cna
Figure 14.24 Atamewthene comboboxlgropdounlst/andoneputbuton
ference betven the two isin how the choice ate presented othe wer Another
ame for acombo box sa drop-iown lis which is more desenpive ofits interaction
‘Syl, Figre 14.24 show a frame with one como box and one piston.
‘We can construct « new JCombotox by passing an array of String objects, or
example
steingt) conepoxtten
Tose, "city temaltealies, #a8a"y
onbetox conbotex ~ new Jconbebox(conbeboxtter)
A scombotox object generates both ation events and item even. An ation
event it generated ever time a Combat is licked (ote it not thal commen (|
process scion events of JCombotax). Bvery time an item different rom the eur
ently selected item is selected, item event is generated and the emstate
Changed method is called twice. The St tine is forthe deselection ofthe curently
scoot item, andthe second is forthe selection ofthe new sem, Notie that whe
the same item is selected agen, no item events generated
‘To in ou the curently selecied item, we call the getSeleceaem method of
2combotox. Because there typ ofthis method i Objet. we mus ypecast ©
the comet type or this example stems ae tring objects o we write
string selection = (string) conbopex.gerselecceateen()s
‘Aso, we can call the getSelecedindex msthod to retrieve the poston of the se
lected item The fet stem in thelist at poston 0
Here's the Ch14)ComboRoxSample class
eeprivate static finel int SRAMEYLUAIGIN ~ 250;
public static void masn{steingt) sess) ¢
catsztansotentansie tane - new G>i¢%GonboBexsanpie()
feane.cettsssble (esse)
public ehisJconbedensanete() ¢
Sessnel) combozonttem =< (yaest, “Hits
pecsize | (FRAME_KIDTL, PRAME_MEIGUT»
Secticie _(SHrogran enatonbaboxsanee")
Setdecat Len (ERAME ORIGIN, POU" ORSSIN
contentPane = getcontentPanet >:
concent?ane.setlayost (new Boedectayou (1)
conboPane: = new JPanel (new FlowLayost ())
conbotane! eet order (9oraesFacory -ereate"itiedorde:(
selon your faversce"))2
conboton = new 2cenbotox (eonsetentten)
onuebon.sduttenttatener(Ehsa);
comuePane: adaleonboPex)¢
oxfenel = new oPanel (new Flow eyeut (192
Gkbutten = new JBucton (Ox),
Sxbutten,saanctlonListenes (enka)
Shtanet adafonsutton) +
contentPane.aid(conboPanel, Borderiayout CENTER);
Gontent?ane.saa(okeanel, Becderisyout 50073)
250 chaperte a
petefsuleCloseoveratson(Ex1i 08 CLOSE);
,
public void secionPertorned{hetionsvent event) ¢
savorite = (string) come2or. getselecteattem(};
loc = conbouex.gecseiecvealnsex()?
ope enbane.showieesageDsatog this, “Currentay selected Leer 17 #
favorite # *" is a inden position " * 100)s
,
public void (tensratecanged(ttenvent even) (
Se (event.gesstatechange() w= itenbvent Suiserk) (
pease ~~“
"event ger iteni) +
caraetrty)
ist
‘The dist class is useful when we need to dxpay ist of items for example, a ist,
cof students, ist of files, and 30 forth. Figure 1425 shows a fame with one Just
listing animals wit thee-eter names and one pushbutton
‘We can construct aJist object in a manner identical tthe way we construct
3combotox objet thal is, by passing an aay of String, such as
Steingl] sanee = ("ape%, “Batty ee", teats,
guise Let = new atist team
‘With Js, we have an opsion of specifying one ofthe three seletion modes:
single-sclecton, singlenteval, and mulipe-nterval. The single-selection mode
allows te seo selet only one tem a atime. The single-interval mode allows he
‘ser to select single contiguous interval. And the milpl-nterval mode allowsFigure 14.25 A/rame wih enelit and one pushbuton
the user to sleet multiple contiguous interval (ach interval will inch one oF|
‘more jem). The muliple-intrval mode ithe default mode. The following thee
aemnente show how to tthe thee selection modes!
ae erselect ontiode (
stseleetsontosel SohcLE sEszersoM)
ise. setseleet iontode
Listselect igntosed INGLE INTERVAL $512€710N)
Lit aerselect Lente (
lst se eet lentodel .MULTIPS_SWTERVAE_SELEET=OM ;
Because muliple items can be selected, we use getSelecedValues and
getSelecteindies to ereve an aray of selected items and an ara of the indices
Of the selected items, respectively. The following code will display the selected
ems and their index postions
object (d saner
Snel) tee
lor = Lise gerselectestnaices ())
for (ine {> 0; 4 < neme-tengehs S64) ¢
syeten.out.prisein((sezing) name(s] +
se position * ¢ Lect):
‘The return ype of getSelectedVelues ita ata of Object, 0 we typecast each item
tn the name arty to steng before printing it on System out. If we know the slee
tion mode is single selection. then we can use getelectedValue and get-
Selectednder instead. Notice inthe code that we are Roading a JLst object di
really to panel. Instead, we wrap itn a JSerolPane and add this ScrellPane toa
Panel becase Js self doesnot ince sroll bas.
282 chaperte a
Here's the Cht4iLitsample clas:
——_—— eee
“mplenants ActionLictener {
public static void main(strinat) azael (
ChLATELotsampie Coave = new ChIATLLeESanp Le 4
frame. sotViazble (truely
public chisztisteanple() ¢
nat] nares = ("Aeet, “Batt, "Beet, eat,
petsize (GAME RID", FRAME BEIGE) 2
petricie (*Proqren eniuulasesanele2")
setLocet ion #Ai¥2_JVORICIN, FRAME! ORIEIN)
contentPane = gatContentPane( 12
eomcentP ane, ae: Baek qos (C010! WHITE)»
corcentPare.setiayout (new Porder"ayout (09%
Listanel ~ new JPne: (new Geidbayou: (0,101;
Nstbanel settorser (Borde-Tactory erestelisledborser(
Sthzee ietter Anumal Nanes"));
Laat = mew ssa tranend
Listeanel sddtnew s8evoLlPane (148095few dared fnew Flowiayout (194
okwattan = new Jeatten eo");
Sknuteon-aadncciontistener (this);
content Pane.sdd(2ietPanel, SordestayeutcoN22R) 7
contenePare eds(ekPane=, berdeslyeu-5207H7
joneOperat ton (EXIT_ON-CLOSE); _
epee) sane:
See) oer
sane ~ List qetselectedvaives()
doe’ = Lise qersedeeteateaces (};
Syaten.outpeintn{osrently selected aninal names ate");
for (ine 1 = 0; 1 = nanersengehy 1-4)
syoten.out printin((strieghrame(.] + ° at position" + leet};
1
,
Jslider
“The sSlider clas cepresents slider in which the user ean mave a nob to a dested
position. The poston of the nob on a slider determines the selected value. Fig:
tee 14.26 shows « frame wit tree sliders. This is a classic example of sliders
Where the user moves the thee aobs to set the red, grees, blue (RGB) value in|
selecting a color. Values forthe RG, and B range itm Ot 285, inclusive. Some
ot properties we ean set for Sir object are the minimum and maximum range
fof values, whether to display the ick mark, the spacing of major std minot tick
tmatks, wheter to display the label forthe major ck marks, and the placement
restation either vertial ot horizontal)
‘The sliders inthe sample program are created and inialized inthe following
UsLider hides = new astiaer(s
eider. setOrLentat on (JS2ider. VERTICAL) +
Slider aetPaineLabels (eras)? //ahow viek
der aetPainetiens(erua)} //ahow “ies
Figure 14.26 tame with vee vrais fer seting an RGB ah,
Lider cetasninan (it CoLoR)
Fliger. settaxinan (HASLEOLO
Slider setVelueQX£:08) 7 //instial poe.
SLiger setilajorTiendpacie (30)?
Sliaer setiiaertienseaeins 5)
‘When a nobis moved, alder object generates a change event (his event oceus|
‘when there's a change in the event source, such asthe nob is moved) To process
change evens, we must register change eveat listeners toa sider event source
‘object. The class that implements the ChangeLisener interface mst define a
method called stateChanged, whose parameter isan instance of Changetvent For
this program, whenever a change event is generated, we read the vale fom each
slide and se the background ofa panel tou designated color Here's the body of
the sateChanged method
2» eastider.getvaiue ():
© greensisaer getVaive
5 = piuestider.gervelue();
coLesPanel setBackgroundinaw Coloe (RG B11Here's the h14ssidersample cas:
De
File: chttasiidersanete, dave
ieport javaw owing."
Gaplenenes changeniatener (
Beivete sectie final ine Feastjcouemn > ior
public static void main(stringt args) (
Chidilidersanple ‘rane ~ new chidsS1:dersanple()
frame. servisinie (seve)?
public chiiJelidertenple( ) (
aecSize, GRAME_AEDTE, FRAME_SEIGHTD ;
fectisle ("Progra ehldutieelanese"})
Jetbocation (FRAME XLOALCIN, FAR_Y_ORISIN):
contentbase = getcontenttane (7
ontenttane. oe: Baexgrouna (Colo! WH°TE)
onventPane.se:Laveut (new Borderiayent (1) 4
aliaesPane! = new Pane {new Flowtayeut (195
slidestane!.setharder (aordectactory createtitledsorder(
Saco Soler Selection");
pectiiges = exeatesiides (HX COLO)»
Greenstider = crestessider (WAX_cOL0N
BluesLider = erestesiider (AK E0308)
sliderPane! ada (reds ert
Plidesrare! saa (geeersisaes)
piidesranel eaa(aivessidee):
colortanel = new JPanel ( 17
colorvanel setheckaround (Cote white)
colerpanel astboraer feorderFactery ,createLeveredsavelBordex()
eontentPane, saa(eolorPapely BoraerLayo™ CENTER);
cortentPane.soa(sliser?anel, Rordertayout EST):
[fsagieter ‘exit vpan closing! az a detssls
petbesaulcCloseogerst on (E1108 ¢L95E)
,
public void statechensea Changesvent event) (
R= regslider geevaise()
5 = geeensiider.geeva se ()s
B= Bluestsaer.geevaiue(};
colortanet seteckgroundinew Colozt8y S811
,
oalider lider = new ostider()s
sides setcetensatian (JS1Ssee.VERIZEAL)
Pliges serPasse lapels (ere) 5
Slides setPasnt Ticks (rue):
Sides section (IM CODDRD 5
Sider. secteanimun (NARLCOLOR
Eiides aeciasae(eatuels
lider sects jortiekspueing 50)
Edides aeuitinesviekspocing 25)
lider aadehengeListenes (2082) ¢=== og
14.8 | Menus
Practical programs with « graphical wer interface wil almost always suppor
menus. In ths section we will deseribe how to display menus and process ment
vents by using JMenu, Menulter, and JMenuBar from the jvaxwing package,
Let's wate a sample code to Hlustate the display of menus andthe processing of
rent item selections, We will esate two mens, Hl and Eat, with the following
ae
cu
open. omy
Sow Paste
Som hs
uit
ihe menstem Quits selected, then we terminate the program, When amen item
ter than Quit is selected, we print a mestage tha denies the relected ment
tem, fr example,
Figure 14.27 shows a Chi A/Menuframe when tis rt opened and after the men
choice Save is clectd
‘One possibie sequence of steps to create and add menvs is this
1 Create a Menutar object and attach i oa fame
2 Create a Menu abject.
1. Create Menultem object and ad them tothe Menu objec.
44 Attach the Menu object tothe IMenudar object.
=== og
Figure 14.27 Cx1aimenuframe window when its fst pened andafler the menuitem Save selected
‘We will create two JMenu object: fleMene and edtMenu, We rete a fe
Menu object
iletiens = new siens(tPile";
‘The argument tothe /Menu constructor isthe name ofthe menu. After the menu is
crested, we ad a mens tem ot Ament tem is he even source of men selection,
so we need to register an setion histener lo every meni ilem we add le men. In
this sample coda, we wil lt a Cht4lMenuframe objec be the action listener of al
tment tems. To create and add amen item New to fileMenu, we execute
ton = new omenatcem en"); (Mew
Hten-addhetlontiscenes (hia);
Fuleese-add(se=1?
‘We repeat his sequence for al other mens items. Meni items ae placed fom
the topin the order they ae added tothe menu, We can als inchde a horizontal line
‘asa separator Between menu items by calling the tnenn’sadaSeparater method,
ilettens.addseparatert)
Ager te mene and their men items aze crested, we attach hem o & ment
‘bar the constructor, we create a/MenuBar objet attach itt the frame by calling
the fame’s seeMenudarmetod, and adé these two JMenu objects to the menu bat
setheribar tnenaas) attach {2 te the teane
‘To display which men item was selected, we use «JLabel object response
We ade response fo the frame by
response = naw dLapel{tielle, this i# your menu testers",
Feaponse-aetsize (260, 50),
‘When a menu item is selected, the registered action listener's acionPerformed
method isclle, The actonPerformed method ofthe Chi4)MenuFrame is defined =
Iollows: It an event souree is + ment sem, the getActionCommand method of
‘Actontventretins the menu's ext, We les if he felurned txt 3 Quit. itis we
terminate the program, Otherwise, we set the txt of response to indicate which
‘ent tern wat selected. Here's the method body of actonPerformed
emslone = event getActsontonmandt)
AE (oenatiane equals ("Quit") (
Syecenexie()yatze (
Tesponce.cettent (titers iten ‘7 + genuine +
Ge celeccea")
Here's the complete Cht4)Menuframe prog:
——
Public static veld main @tringil
ChikensPrane Frame ~ new hdNens rane (7
rane. setViaibte (ervey
pobite ChiesmenuFrame ) (
fecticie (entsimerurrane’}s
Seecize (FRAME WIOTU, FRAME EIGN)
Setaesizabie false);
Settecat Lon (PRAME_ALORIGIN, §RAME_Y_ORIGIM 7
contentPane = getcontentPane )
content Pane. seziayout (new Flowtayout ))1
eresteriievens()p
ceeatenauens