Upload
vuongduong
View
237
Download
1
Embed Size (px)
Citation preview
CPE2
03/C
SC20
3So
ftw
are
Syst
ems
and
Mod
els
CPE2
03/C
SC20
3So
ftw
are
Syst
ems
and
Mod
els
Get
ting
Star
ted
with
Jav
a G
UI
Prog
ram
min
gG
ettin
g St
arte
d w
ith J
ava
GU
I Pr
ogra
mm
ing
Dr
Zhou
Sui
ping
Off
ice:
N4-
02-C
87Ph
one:
679
0 62
63Em
ail:
assp
zhou
@nt
u.ed
u.sg
Dr
Zhou
Sui
ping
Off
ice:
N4-
02-C
87Ph
one:
679
0 62
63Em
ail:
assp
zhou
@nt
u.ed
u.sg
2
How
thi
s pa
rt w
ill b
e ta
ught
?H
ow t
his
part
will
be
taug
ht?
Java
GU
I pr
ogra
mm
ing
is N
OT
the
focu
s of
thi
s su
bjec
t, it
is u
sed
to il
lust
rate
maj
or c
once
pts
and
tech
niqu
es in
eve
nt-d
riven
par
adig
m a
nd m
odel
s.Th
eref
ore,
we
will
NO
T di
scus
s Ja
va G
UI
prog
ram
min
g in
muc
h de
tail
and
syst
emat
ical
lyW
e on
ly d
iscu
ss s
ome
very
bas
ic f
eatu
res
in
Java
GU
I pr
ogra
mm
ing.
Lear
n th
roug
h pr
actic
e: L
ab 1
and
Lab
2.
Java
GU
I pr
ogra
mm
ing
is N
OT
the
focu
s of
thi
s su
bjec
t, it
is u
sed
to il
lust
rate
maj
or c
once
pts
and
tech
niqu
es in
eve
nt-d
riven
par
adig
m a
nd m
odel
s.Th
eref
ore,
we
will
NO
T di
scus
s Ja
va G
UI
prog
ram
min
g in
muc
h de
tail
and
syst
emat
ical
lyW
e on
ly d
iscu
ss s
ome
very
bas
ic f
eatu
res
in
Java
GU
I pr
ogra
mm
ing.
Lear
n th
roug
h pr
actic
e: L
ab 1
and
Lab
2.
3
Out
line
Out
line
GU
I Cl
ass
Hie
rarc
hy (
AWT
& S
win
g)M
ajor
ste
ps a
nd f
eatu
res
in J
ava
GU
I Fr
ames
, pan
els,
layo
ut m
anag
ers
Dra
win
g on
Pan
els
Dra
win
g ge
omet
ric s
hape
s
GU
I Cl
ass
Hie
rarc
hy (
AWT
& S
win
g)M
ajor
ste
ps a
nd f
eatu
res
in J
ava
GU
I Fr
ames
, pan
els,
layo
ut m
anag
ers
Dra
win
g on
Pan
els
Dra
win
g ge
omet
ric s
hape
s
4
Firs
t, h
ave
som
e fe
elin
g of
so
me
GU
I ob
ject
s!Fi
rst,
hav
e so
me
feel
ing
of
som
e G
UI
obje
cts!
// C
reat
e a
butt
on w
ith
text
OK
JButton
jbtOK
= new JButton("OK");
// C
reat
e a
labe
l an
d a
chec
k bo
xJLabel
jlblName
= new JLabel("Enter
your name: ");
JCheckBox
jchkBold
= new JCheckBox("Bold");
// C
reat
e a
radi
o bu
tton
and
a t
ext
fiel
dJRadioButton
jrbRed
= new RadioButton("Red");
…
Text
Fiel
dC
ombo
Box
5
Som
e hi
stor
y: A
WT
vs. S
win
g So
me
hist
ory:
AW
T vs
. Sw
ing
Why
do
som
e G
UI
com
pone
nt c
lass
es h
ave
a J-
pref
ix?
Inst
ead
of
usin
gJB
utto
n , w
hy n
ot s
impl
y na
me
it Bu
tton
?
In f
act,
the
re is
a c
lass
alre
ady
nam
ed B
utto
n in
the
ja
va.a
wt
pack
age.
Whe
n Ja
va w
as in
trod
uced
, the
GU
I cl
asse
s w
ere
bund
led
in
a lib
rary
kno
wn
as t
he A
bstr
act
Win
dow
s To
olki
t (A
WT)
.AW
T is
fin
e fo
r de
velo
ping
sim
ple
GU
I, b
ut n
ot f
or
com
preh
ensi
ve G
UI
proj
ects
.W
ith t
he r
elea
se o
f Ja
va 2
, the
AW
Tus
er-in
terf
ace
com
pone
nts
wer
e re
plac
ed b
y a
mor
e ro
bust
, ver
satil
e, a
nd
flexi
ble
libra
ry k
now
n as
Sw
ing
com
pone
nts.
In f
act,
the
re is
a c
lass
alre
ady
nam
ed B
utto
n in
the
ja
va.a
wt
pack
age.
Whe
n Ja
va w
as in
trod
uced
, the
GU
I cl
asse
s w
ere
bund
led
in
a lib
rary
kno
wn
as t
he A
bstr
act
Win
dow
s To
olki
t (A
WT)
.AW
T is
fin
e fo
r de
velo
ping
sim
ple
GU
I, b
ut n
ot f
or
com
preh
ensi
ve G
UI
proj
ects
.W
ith t
he r
elea
se o
f Ja
va 2
, the
AW
Tus
er-in
terf
ace
com
pone
nts
wer
e re
plac
ed b
y a
mor
e ro
bust
, ver
satil
e, a
nd
flexi
ble
libra
ry k
now
n as
Sw
ing
com
pone
nts.
So,w
ithou
t J-
pref
ixar
eAW
TG
UI
obje
cts;
with
J-p
refix
are
Swin
gG
UI
obje
cts.
6
For
your
info
rmat
ion:
Jav
a G
UI
clas
s hi
erar
chy
For
your
info
rmat
ion:
Jav
a G
UI
clas
s hi
erar
chy
Dim
ensi
on
Font
Font
Met
rics
Com
pone
nt
Gra
phic
s
Obj
ect
Col
or
Con
tain
er
Pane
lA
pple
t
Fram
e
Dia
log
Win
dow
JCom
pone
nt
JApp
let
JFra
me
JDia
log
Swin
g C
ompo
nent
sin
the
java
x.sw
ing
pack
age
Cla
sses
in th
eja
va.a
wt p
acka
ge1
Layo
utM
anag
er
*
7
For
your
info
rmat
ion:
bas
ic
Swin
g G
UI
com
pone
nts
For
your
info
rmat
ion:
bas
ic
Swin
g G
UI
com
pone
nts
JM
enuI
tem
JC
heck
Box
Men
uIte
m
Abst
ract
Butto
n
JCom
pone
nt
JM
enu
JR
adio
But
tonM
enuI
tem
JTo
ggle
But
ton
JC
heck
Box
JRad
ioB
utto
n
JC
ombo
Box
JIn
tern
alFr
ame
JLa
yere
dPan
e
JLi
st JM
enuB
ar
JO
ptio
nPan
e
JPo
pupM
enu
JPr
ogre
ssB
ar
JFi
leC
hoos
er
JSc
rollB
ar
JSc
rollP
ane
JSe
para
tor
JSp
litPa
ne
JSl
ider
JTa
bbed
Pane JTa
ble
JTa
bleH
eade
r
JTex
tFie
ld J
Text
Com
pone
nt
JTe
xtA
rea
JTo
olB
ar J
Tool
Tip
JTr
ee
JR
ootP
ane
JPa
nel JPa
ssw
ordF
ield
JC
olor
Cho
oser
JLa
bel
JEd
itorP
ane
JSp
inne
r
JB
utto
n
8
Gen
eral
ste
ps in
cre
atin
g G
UI
Gen
eral
ste
ps in
cre
atin
g G
UI
Crea
te a
fra
me
Fram
e is
the
bas
is t
o co
ntai
n ot
her
GU
I co
mpo
nent
s, s
uch
as b
utto
ns, …
Add
GU
I co
mpo
nent
s in
to t
he c
onte
nt
pane
of
the
fram
eU
se p
rope
r La
yout
Man
ager
to
arra
nge
the
com
pone
nts
Crea
te a
fra
me
Fram
e is
the
bas
is t
o co
ntai
n ot
her
GU
I co
mpo
nent
s, s
uch
as b
utto
ns, …
Add
GU
I co
mpo
nent
s in
to t
he c
onte
nt
pane
of
the
fram
eU
se p
rope
r La
yout
Man
ager
to
arra
nge
the
com
pone
nts
9
Crea
ting
Fram
esCr
eatin
g Fr
ames
import javax.swing.*;
public class MyFrame
{public static void main(String[] args)
{JFrame
frame = new JFrame(“MyFrame");
frame.setSize(400, 300);
frame.setVisible(true);
//ex
it t
he p
rogr
am u
pon
clos
ing
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}} Ru
n
10
Addi
ng c
ompo
nent
s in
to a
fra
me
Addi
ng c
ompo
nent
s in
to a
fra
me
// A
dd a
but
ton
into
the
fra
meframe.getContentPane().add( new JButton(“click
me"));
Con
tent
pan
e
A fr
ame
uses
its
cont
ent
pane
to
hol
d co
mpo
nent
s in
the
fr
ame.
Title
bar
frame.setTitle(“MyFrame”);
frame.getContentPane();
Run
11
Cent
erin
g fr
ames
Cent
erin
g fr
ames
scre
enH
eigh
t
scre
enW
idth
getH
eigh
t()
getW
idth
()
(x, y
)
Fram
e
(0, 0
)
By d
efau
lt, a
fra
me
is d
ispl
ayed
in t
he u
pper
-left
cor
ner
of
the
scre
en.
To d
ispl
ay a
fra
me
at a
spe
cifie
d lo
catio
n, u
se t
he
setL
ocat
ion(
x, y
)m
etho
d in
the
JFr
ame
clas
s. T
his
met
hod
plac
es t
he u
pper
left
cor
ner
of a
fra
me
at lo
catio
n (x
, y).
By d
efau
lt, a
fra
me
is d
ispl
ayed
in t
he u
pper
-left
cor
ner
of
the
scre
en.
To d
ispl
ay a
fra
me
at a
spe
cifie
d lo
catio
n, u
se t
he
setL
ocat
ion(
x, y
)m
etho
d in
the
JFr
ame
clas
s. T
his
met
hod
plac
es t
he u
pper
left
cor
ner
of a
fra
me
at lo
catio
n (x
, y).
12
Cent
erin
g fr
ames
(Co
nt’d
)Ce
nter
ing
fram
es (
Cont
’d)
import javax.swing.*;
import java.awt.*;
public class CenterFrame{
public static void main(String[] args) {
JFrame
frame = new JFrame("CenterFrame");
...
// Get the coordinate (x, y)
Dimension screenSize
=Toolkit.getDefaultToolkit().getScreenSize();
intx = (screenSize.width
-frame.getWidth()) / 2;
inty = (screenSize.height-
frame.getHeight()) / 2;
// place the frame to the center of the screen
frame.setLocation(x, y);
frame.setVisible(true);
}
}
Run
13
Usi
ng p
rope
r La
yout
Man
ager
to
arra
nge
GU
I co
mpo
nent
s U
sing
pro
per
Layo
ut M
anag
er t
o ar
rang
e G
UI
com
pone
nts
The
GU
I co
mpo
nent
s ar
e pl
aced
in c
onta
iner
s.Fo
r ex
ampl
e, t
he c
onte
nt p
ane
of a
fra
me
is a
con
tain
er.
Each
con
tain
er h
as a
layo
ut m
anag
erto
arr
ange
the
G
UI
com
pone
nts
with
in t
he c
onta
iner
.
Use
the
set
Layo
ut(L
ayou
tMan
ager
)m
etho
d to
ch
oose
a p
rope
r La
yout
Man
ager
in a
con
tain
er.
Diff
eren
t ty
pes
of L
ayou
t M
anag
ers
Flow
Layo
utG
ridLa
yout
Bord
erLa
yout
The
GU
I co
mpo
nent
s ar
e pl
aced
in c
onta
iner
s.Fo
r ex
ampl
e, t
he c
onte
nt p
ane
of a
fra
me
is a
con
tain
er.
Each
con
tain
er h
as a
layo
ut m
anag
erto
arr
ange
the
G
UI
com
pone
nts
with
in t
he c
onta
iner
.
Use
the
set
Layo
ut(L
ayou
tMan
ager
)m
etho
d to
ch
oose
a p
rope
r La
yout
Man
ager
in a
con
tain
er.
Diff
eren
t ty
pes
of L
ayou
t M
anag
ers
Flow
Layo
utG
ridLa
yout
Bord
erLa
yout
14
Flow
Layo
utM
anag
erFl
owLa
yout
Man
ager
The
com
pone
nts
are
arra
nged
fro
m le
ft t
o rig
ht in
th
e or
der
in w
hich
the
y w
ere
adde
d. W
hen
one
row
bec
omes
fill
ed, a
new
row
is s
tart
ed.
15
Flow
Layo
utM
anag
er (
Cont
’d)
Flow
Layo
utM
anag
er (
Cont
’d)
import javax.swing.*;
import java.awt.*;
public class ShowFlowlayoutextends JFrame{
public ShowFlowLayout() {
// Get the content
pane of the frame
Container container = getContentPane();
// Set FlowLayout, aligned left with horizontal gap 10 and vertical gap 20
// between components
container.setLayout(newFlowLayout(FlowLayout.LEFT, 10, 20));
// Add buttons to the frame
for (int
i = 1; i <= 10; i++) container.add(newJButton("Component
" + i));
} public static void main(String[] args) {
ShowFlowLayout
frame= new ShowFlowLayout();
} }Ru
n
frame.setSize(200, 500);
Size
of t
he
cont
aine
r mat
ters
Run
frame.setSize(400, 500);
16
For
your
info
rmat
ion:
mor
e de
tails
on
Flo
wLa
yout
Cons
truc
tors
For
your
info
rmat
ion:
mor
e de
tails
on
Flo
wLa
yout
Cons
truc
tors
publ
ic F
low
Layo
ut(in
tal
ign,
int
hGap
, int
vGap
)Co
nstr
ucts
a n
ew F
low
Layo
utw
ith a
spe
cifie
d al
ignm
ent,
ho
rizon
tal g
ap, a
nd v
ertic
al g
ap. T
he g
aps
are
the
dist
ance
s in
pix
el b
etw
een
com
pone
nts.
publ
ic F
low
Layo
ut(in
tal
ign)
Cons
truc
ts a
new
Flo
wLa
yout
with
a s
peci
fied
alig
nmen
t an
d a
defa
ult
gap
of f
ive
pixe
lsfo
r bo
th h
oriz
onta
l and
ver
tical
.pu
blic
Flo
wLa
yout
()Co
nstr
ucts
a n
ew F
low
Layo
utw
ith a
def
ault
cent
er a
lignm
ent
and
a de
faul
t ga
p of
five
pixe
lsfo
r bo
th h
oriz
onta
l and
ve
rtic
al.
17
Grid
Layo
utM
anag
erG
ridLa
yout
Man
ager
Arra
nges
com
pone
nts
in a
grid
(m
atrix
) fo
rmat
ion
with
the
num
ber
of r
ows
and
colu
mns
def
ined
by
the
cons
truc
tor .
publ
ic G
ridLa
yout
(int
row
s, in
tco
lum
ns):
cons
truc
tsa
new
Grid
Layo
utw
ith t
he s
peci
fied
num
ber
of
row
s an
d co
lum
ns.
publ
ic G
ridLa
yout
(int
row
s, in
tco
lum
ns, i
nthG
ap,
int
vGap
):fu
rthe
r w
ith s
peci
fied
horiz
onta
l and
vert
ical
gap
s be
twee
n co
mpo
nent
s.
Arra
nges
com
pone
nts
in a
grid
(m
atrix
) fo
rmat
ion
with
the
num
ber
of r
ows
and
colu
mns
def
ined
by
the
cons
truc
tor .
publ
ic G
ridLa
yout
(int
row
s, in
tco
lum
ns):
cons
truc
tsa
new
Grid
Layo
utw
ith t
he s
peci
fied
num
ber
of
row
s an
d co
lum
ns.
publ
ic G
ridLa
yout
(int
row
s, in
tco
lum
ns, i
nthG
ap,
int
vGap
):fu
rthe
r w
ith s
peci
fied
horiz
onta
l and
vert
ical
gap
s be
twee
n co
mpo
nent
s.
18
Grid
Layo
utM
anag
er (
Cont
’d)
Grid
Layo
utM
anag
er (
Cont
’d)
public class ShowGridLayoutNewextends JFrame{
public ShowGridLayoutNew() {
Container container= getContentPane();
//set GridLayout, 3 rows and 2 columns
container.setLayout(newGridLayout(3, 2, 5, 5));
// Add labels and text fields to the frame
container.add(newJLabel("FirstName"));
container.add(newJTextField(8));
container.add(newJLabel("MI"));
container.add(newJTextField(1));
container.add(newJLabel("Last
Name"));
container.add(newJTextField(8));
} public static void main(String[] args) {
ShowGridLayoutNewframe =
new ShowGridLayoutNew();
...
}}
Run
19
Bord
erLa
yout
Man
ager
Bord
erLa
yout
Man
ager
Div
ides
the
con
tain
er in
to f
ive
area
s: E
ast,
Sou
th,
Wes
t, N
orth
, and
Cen
ter.
Com
pone
nts
are
adde
d by
usi
ng t
he a
dd m
etho
d ad
d(Co
mpo
nent
, con
stra
int)
, whe
re c
onst
rain
t is
Bo
rder
Layo
ut.E
AST,
Bor
derL
ayou
t.SO
UTH
, Bo
rder
Layo
ut.W
EST,
Bor
derL
ayou
t.N
ORT
H, o
r Bo
rder
Layo
ut.C
ENTE
R.
publ
ic B
orde
rLay
out(
int
hGap
, int
vGap
)or
publ
ic B
orde
rLay
out(
)
Div
ides
the
con
tain
er in
to f
ive
area
s: E
ast,
Sout
h,W
est,
Nor
th, a
nd C
ente
r.
Com
pone
nts
are
adde
d by
usi
ng t
he a
dd m
etho
d ad
d(Co
mpo
nent
, con
stra
int)
, whe
re c
onst
rain
t is
Bo
rder
Layo
ut.E
AST,
Bor
derL
ayou
t.SO
UTH
, Bo
rder
Layo
ut.W
EST,
Bor
derL
ayou
t.N
ORT
H, o
r Bo
rder
Layo
ut.C
ENTE
R.
publ
ic B
orde
rLay
out(
int
hGap
, int
vGap
)or
publ
ic B
orde
rLay
out(
)
20
Bord
erLa
yout
Man
ager
(Co
nt’d
)Bo
rder
Layo
utM
anag
er (
Cont
’d)
public class ShowBorderLayout
extends JFrame{
public ShowBorderLayout() {
Container container= getContentPane();
// Set BorderLayout
container.setLayout(newBorderLayout(5, 10));
// Add buttons to the frame
container.add(newButton("East"), BorderLayout.EAST);
container.add(newJButton("South"), BorderLayout.SOUTH);
container.add(newJButton("West"), BorderLayout.WEST);
container.add(newJButton("North"), BorderLayout.NORTH);
container.add(new
JButton("Center"), BorderLayout.CENTER);
} public static void main(String[] args) {
ShowGridLayout
frame = new ShowBorderLayout();
...
}}
Run
21
An im
port
ant
tech
niqu
e: u
sing
Pa
nels
as
sub-
cont
aine
rsAn
impo
rtan
t te
chni
que:
usi
ng
Pane
ls a
s su
b-co
ntai
ners
It is
rec
omm
ende
d th
at t
he u
ser
inte
rfac
e co
mpo
nent
s be
pla
ced
in p
anel
s an
d th
en t
he p
anel
s be
plac
ed in
a f
ram
e.
// create a panel with a default
// FlowLayoutmanager
JPanel
p2 = new JPanel();
// add a component to the panel
p2.add(new JTextField("Timeto
be displayed here");
P2.add(p1);
A co
mpo
nent
is a
dded
to
the
cont
ent
pane
of
a fr
ame,
whe
reas
a c
ompo
nent
is d
irect
lyad
ded
to a
pan
el.
p1p2
22
Usi
ng P
anel
s as
sub
-Con
tain
ers
(Con
t’d)
Usi
ng P
anel
s as
sub
-Con
tain
ers
(Con
t’d)
public class TestPanelsextends JFrame{
public TestPanels() {
// Create panel p1
for the buttons
JPanelp1 = new JPanel(newGridLayout(4, 3));
//Add buttons to the panel
for (int
i = 1; i <= 9; i++)
p1.add(new JButton("" + i));
p1.add(new JButton("" + 0));
p1.add(new JButton("Start")); p1.add(new JButton("Stop"));
// Create panel p2 to hold a text field and p1
JPanelp2 = new JPanel(newBorderLayout());
p2.add(new JTextField("Time
to be displayed here"),BorderLayout.NORTH);
p2.add(p1, BorderLayout.CENTER);
// Add p2 and a button to the frame
Container container= getContentPane();
container.setLayout(newBorderLayout());
container.add(p2, BorderLayout.EAST);
container.add(newJButton("Foodto be placed here"
),BorderLayout.CENTER);
} public static void main(String[] args) {
TestPanelsframe = new TestPanels();
}}
Run
A b
utto
n
A te
xtfie
ld
12bu
ttons
fram
e
p2 p1
23
Dra
win
g on
a P
anel
Dra
win
g on
a P
anel
Pane
l can
be
used
to
draw
gra
phic
s.
To d
raw
in a
pan
el:
crea
te a
new
cla
ss t
hat
exte
nds
JPan
elan
dov
errid
e th
e pa
intC
ompo
nent
(Gra
phic
sg)
met
hod
to t
ell
the
pane
l how
to
draw
diff
eren
t ty
pes
of o
bjec
ts.
disp
lay
strin
gs, d
raw
geo
met
ric s
hape
s, a
nd v
iew
imag
es
on t
he p
anel
.
Pane
l can
be
used
to
draw
gra
phic
s.
To d
raw
in a
pan
el:
crea
te a
new
cla
ss t
hat
exte
nds
JPan
elan
dov
errid
e th
e pa
intC
ompo
nent
(Gra
phic
sg)
met
hod
to t
ell
the
pane
l how
to
draw
diff
eren
t ty
pes
of o
bjec
ts.
disp
lay
strin
gs, d
raw
geo
met
ric s
hape
s, a
nd v
iew
imag
es
on t
he p
anel
.
24
Dra
win
g on
a P
anel
(Co
nt’d
)D
raw
ing
on a
Pan
el (
Cont
’d)
A sk
elet
on o
f im
plem
entin
g th
epa
intC
ompo
nent
(Gra
phic
sg)
met
hod:
prot
ecte
d vo
id p
aint
Com
pone
nt(G
raph
ics
g) {
supe
r.pa
intC
ompo
nent
(g);
//dr
aw s
omet
hing
her
eg.
draw
Strin
g(“W
elco
me
to J
ava!
”, 4
0, 4
0);
} The
Gra
phic
s ob
ject
gis
cre
ated
aut
omat
ical
ly b
y th
e JV
M.
Use
var
ious
dra
win
g m
etho
ds d
efin
ed in
the
Gra
phic
scl
ass
to d
raw
str
ings
, geo
met
ric f
igur
es, o
r im
ages
.
25
Dra
win
g a
strin
g D
raw
ing
a st
ring
public class DrawMessage
extends JPanel
{
public static void main(String[] args) {
JFrame
frame = new JFrame("DrawMessage");
frame.getContentPane().add(new
DrawMessage());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
} /** Paint the message */
protected void paintComponent(Graphics
g) {
g.drawString(“HelloWorld!", 40, 40);
super.paintComponent(g);
g.drawString("Welcometo Java!", 40, 40);
}}
Run
To e
nsur
e th
at th
e dr
awin
g ar
ea is
cle
ared
bef
ore
a ne
w
draw
ing
is d
ispl
ayed
.
Dra
w th
e st
ring
at
coo
rdin
ate
(40,
40)
Run