You are on page 1of 110

LP TRNH JAVA NNG CAO

Chng 01: Lp trnh giao din


L Tn
B mn: Lp trnh my tnh
i d!ng "hng 01
!
S phn cp lp GUI
!
JFrames
!
Layout Managers
!
Drawing on JPanels: Lines, Rectangles,
Ovals, Arcs, Polygons
!
Event-Driven Programming: Event Source,
Listener, Listener Interface
!
Nt nhn v menu
!
JCheckbBox v JRadioButton
!
Cc lp van ban v JScrollBar
C" th#nh ph$n %&'
!
Cc i tuong GUI: button, label, text
field, check box, radio button, combo
box, .
!
Mi loai i tuong uoc xc inh trong 1
lp: JButton, JLabel, JTextField,
JCheckBox, JRadioButton, JComboBox, .
!
Mi lp thnh phn GUI c mt s
constructor tao cc i tuong thnh
phn GUI.
()ing *+, -.T
!
AWT: Abstract Windows Toolkit:
/
0a*a 1
/
12" g3n *4i p5at6orm 7" 89nh
/
Th"h h2p *4i *i" pht tri:n "" ;ng d<ng %&' 8n gi=n,
!
Swing components:
/
0a*a >
/
?hng g3n *4i p5at6orm "@ 89nh
/
ABnhC 8a nDngC 5inh hoBt
( 8E ph$n "Fp 54p %&' G()ingH

IimJn+ion
Kont
FontMetrics
Component
Graphics
LMNJ"t Co5or
ContainJr
OanJ5 -pp5Jt
KramJ
Iia5og
.indo)
JComponent
0-pp5Jt
0KramJ
0Iia5og
()ing ComponJnt+
in thJ Na*a7,+)ing pa"PagJ
Light)Jight
QJa*y)Jight
C5a++J+ in thJ Na*a,a)t
pa"PagJ
1
LayoutManager
R
JComponent
C" 54p %&': nhSm "ontainJr
!
uoc dung cha cc thnh phn
khc.
!
Cc lp container (Swing):
/
ContainJr
/
0KramJ
/
0Iia5og
/
0-pp5Jt
/
0OanJ5
C" 54p %&': nhSm "omponJnt
!
Gm cc subclass cua lp JComponent.
!
Cc lp GUI component (Swing):
/
0B!tton
/
0LaMJ5
/
0TJ7tKiJ5d
/
0TJ7t-rJa
/
0ComMoBo7
/
0Li+t
/
0TadioB!tton
/
0AJn!
/
U
C" 54p %&': nhSm hJ5pJr
!
uoc cc component v container
dung v v at cc i tuong.
!
Cc lp helper (Swing):
/
%raphi"+
/
Co5or
/
Kont
/
KontAJtri"+
/
IimJn+ion
/
Layo!tAanagJr
-.T GLptiona5H
-.TV*Jnt
Kont
KontAJtri"+
ComponJnt
%raphi"+
LMNJ"t Co5or
Can*a+
B!tton
TJ7tComponJnt
LaMJ5
Li+t
ChJ"PBo7%ro!p
ChJ"PBo7
Choi"J
ContainJr OanJ5 -pp5Jt
KramJ
Iia5og Ki5JIia5og
.indo)
TJ7tKiJ5d
TJ7t-rJa
AJn!ComponJnt
AJn!'tJm
AJn!Bar
AJn!
("ro55Mar
LayoutManager
C" th#nh ph$n giao din ngWi +X d<ng
KramJ O!55Ydo)n AJn!+
&+Jr 'ntJr6a"J
ComponJnt+ G&'H
OanJ5
OanJ5
OanJ5
&'
OanJ5
&'
OanJ5
&'
-pp5Jt
OanJ5
&+Jr 'ntJr6a"J
ComponJnt+
OanJ5
&+Jr 'ntJr6a"J
ComponJnt+
OanJ5
&+Jr 'ntJr6a"J
ComponJnt+
OanJ5
&+Jr 'ntJr6a"J
ComponJnt+
panJ5
O!55Ydo)n AJn!+
KramJ+
!
Frame l mt cua s khng cha
trong cua s khc.
!
Frame l nn tang cha cc thnh
phn GUI khc trong cc ng dng
Java GUI.
!
Trong cc chung trnh Swing GUI,
su dng lp JFrame tao cc cua
s.
TBo KramJ
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Test Frame");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
ChZ [: ChBy "hng trnh "$n 0I? 1,\ ho]" "ao hn
CDn gi^a KramJ

A]" 89nhC 6ramJ 82" hi:n th9 _ gS" trn


Mn tri "`a m#n hnh,

1: hi:n th9 6ramJ _ mt *9 tr 7" 89nhC +X


d<ng phng th;" setLocation(x, y)
trong 54p JFrame,

Ohng th;" n#y 8]t gS" tri trn "`a 6ramJ


tBi *9 tr "S taa 8 G7C yH,
CDn gi^a KramJ GtibpH

+"rJJnQJight
+"rJJn.idth
gJtQJightGH
gJt.idthGH
G7C yH
KramJ
("rJJn
G0C 0H
1a "" th#nh ph$n *#o trong KramJ
// Dua nut bam vao trong frame
frame.getContentPane().add(
new JButton("OK"));
Lc& d
Content pane l mt lp con cua Container.
Cu lnh o slide truc tung ung vi 2
cu lnh sau:
Container container = frame.getContentPane();
container.add(new JButton("OK"));
Content pane uoc sinh ra khi mt i tuong
JFrame uoc tao. i tuong JFrame su dng
content pane cha cc thnh phn trong
frame.
Layo!t AanagJr+
!
Cc layout manager cua Java cung
cp c ch t ng nh xa cc
thnh phn GUI cua ban trn tt ca
cc h thng cua s.
!
Cc thnh phn GUI uoc at trong
cc container. Mi container c mt
layout manager sp xp cc thnh
phn .
Thibt 5p Layo!t AanagJr
LayoutManager layMan = new
XLayout();
container.setLayout(layMan);
!
XLayout:
-
FlowLayout
-
GridLayout
-
BorderLayout
e d< f,1: FlowLayout AanagJr
Cc thnh phn uoc
sp xp trong
container tu tri sang
phai, tu trn xung
dui theo th t chng
uoc ua vo.
FlowLayout Con+tr!"tor+
!
public FlowLayout(int align, int hGap, int vGap)
Xy dng mt FlowLayout mi c cch sp hng
(alignment), khoang trng ngang (horizontal gap),
khoang trng doc (vertical gap) xc inh. Cc khoang
trng gia cc thnh phn uoc tnh bng pixel.
!
public FlowLayout(int alignment)
Xy dng mt FlowLayout mi c alignment xc inh,
khoang trng ngang v doc u c mac inh bng 5
pixel.
!
public FlowLayout()
Xy dng mt FlowLayout mi c cch sp hng mac inh
can gia v khoang trng ngang v doc mac inh bng
5 pixel.
e d< f,>: GridLayout AanagJr
GridLayout manager sp xp cc
thnh phn trong mt lui (ma trn)
vi s hng v s ct uoc xc inh
boi constructor. Cc thnh phn uoc
at trong lui tu tri sang phai, tu
trn xung dui.
GridLayout Con+tr!"tor+
!
public GridLayout(int rows,int columns)
Xy dng mt GridLayout mi c s hng
v s ct xc inh.
!
public GridLayout(int rows, int columns,
int hGap, int vGap)
Xy dng mt GridLayout mi c s hng
v s ct xc inh, v khoang trng
ngang v doc gia cc thnh phn uoc
xc inh.
V d 9.3: BorderLayout
Manager
!
BorderLayout manager chia container thnh 5
khu vc: East, South, West, North, v Center.
V d 9.3 (tip)
!
Cc thnh phn uoc ua vo
BorderLayout bng phung thc add:
add(Component, constraint)
!
constraint:
/
BordJrLayo!t,V-(TC
/
BordJrLayo!t,(L&TQC
/
BordJrLayo!t,.V(TC
/
BordJrLayo!t,LTTQC
/
BordJrLayo!t,CVTVT,
S dng Panel lm Container
!
Cc panel ng vai tr nhu cc container
nho nhm cc thnh phn GUI.
!
Ban nn at cc thnh phn GUI trong cc
panel v at cc panel trong mt frame,
hoac cng c th at panel trong panel.
JPanel p = new JPanel();
p.add(new JButton("OK");
frame.getContentPanel().add(p);
V d 9.4: Panel
Chung trnh tao mt giao din cho l vi
sng, su dng cc panel t chc cc
thnh phn.



- M!tton
- tJ7t6iJ5d

1>
M!tton+
6ramJ
p>
p1
eg trn OanJ5
!
JPanel cn c th uoc su dng v
hoa, van ban v cho php tung tc vi
ngui su dng.
!
v trn panel:
/
TBo mt 54p +!M"5a++ "`a JPanel
/
ChEng phng th;" paintComponent,
/
(a! 8S "S th: hi:n th9 "" "h!hi P[ tiC *g "" Ph@i hnh ha" *#
hi:n th9 =nh trn panJ5,
eg trn OanJ5 GtibpH
public class DrawMessage extends JPanel {
/** Main method */
public static void main(String[] args) {
JFrame frame = new JFrame("DrawMessage");
frame.getContentPane().add(new
DrawMessage());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL
OSE);
frame.setSize(300, 200);
frame.setVisible(true);
}

/** Paint the message */


public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Welcome to Java!", 40, 40);
}
}
eg trn OanJ5 GtibpH
Lc& d
!
Lp Graphics l mt lp truu tuong hin
thi hnh v v anh trn mn hnh trn cc
platform khc nhau.
!
Lp Graphics gi gon cc chi tit platform
v cho php ban v cc th theo cch ging
nhau khng lin quan n cc platform c th.
!
Li goi super.paintComponent(g) l cn
thit am bao rng vung hin thi uoc xa
sach truc khi hin thi mt ban v.
Lc& d
v cc hnh, thng thung ban tao
mt lp con cua JPanel v chng
phung thc paintComponent "ni"
cho h thng phai v nhu th no.
Thc t ban c th v cc th trn
bt ky thnh phn GUI no.
L4p Color
!
Ban c th thit lp mu cho cc thnh phn
GUI bng cch su dung lp java.awt.Color. Cc
mu uoc tao tu 3 mu c ban l red, green,
blue; mi mu uoc biu din boi mt gi
tri byte (0-255) miu ta cung . y uoc
goi l h mu RGB (RGB model).
Color c = new Color(r, g, b);
r, g, b xc inh mt mu uoc tao boi cc
thnh phn tung ng red, green, blue.
V d:
Color c = new Color(228, 100, 255);
Thibt 5p m#!
!
Ban c th su dng cc phung thc sau
thit lp mu background v
foreground cua cc thnh phn:
setBackground(Color c)
setForeground(Color c)
V d:
JButton jbtOK = new JButton();
jbtOK.setBackground(Color.yellow);
jbtOK.setForeground(new Color(255,0,0));
L4p Font
Font myFont = Font(name, style, size);
V d:
Font font1 = new Font("SansSerif", Font.BOLD, 1);
Font font2 = new Font("Serif",
Font.BOLDFont.ITALIC, 12);
Tm tFt "= tn Kont Ph= d<ng
import java.awt.GraphicsEnvironment;
public class testAllFonts {
public static void main(String[] args) {
GraphicsEnvironment e =

GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames =
e.getAvailableFontFamilyNames();
for (int i = 0; i < fontnames.length; i++)
System.out.println(fontnames[i]);
}
}
Thibt 5p Kont
public void paint(Graphics g) {
Font myFont = new Font("Times", Font.BOLD, 18);
g.setFont(myFont);
g.drawString("Welcome to Java", 20, 40);
//set a new font
g.setFont(new Font("Courier",Font.BOLDFont.ITALIC,1));
g.drawString("Welcome to Java", 20, 0);
}
L4p FontMetrics
!
Ban c th hin thi mt chui k t tai vi
tr bt ky trong panel bng cch su dng lp
FontMetrics.
!
nhn i tuong FontMetrics cho mt font
xc inh, su dng phung thc getFontMetrics:
public void paint(Graphics g) {
g.getFontMetrics(Font f); jj ho]"
g.getFontMetrics();
}
C" phng th;" 5Fy th!" tnh "h!hi
"`a 54p FontMetrics
!
public int getAscent()
!
public int getDescent()
!
public int getLeading()
!
public int geteight()
!
public int stringWidth(String str)
e d< f,k: (X d<ng FontMetrics
!
Mc tiu: in thi Welcome to
Java can gia trong frame.

Welome to !a"a
+tring.idth
+tring-+"Jnt
gJtQJightGH
gJt.idthGH
mJ++agJOanJ5
e d< f,k GtibpH

AJ++agJOanJ5

Y7CoordinatJ: int
YyCoordinatJ: int
Y"JntJrJd: Moo5Jan
YmJ++agJ: (tring

lgJtAJ++agJGH: (tring
lgJtmCoordinatJGH: int
lgJtnCoordinatJGH: int
li+CJntJrJdGH: Moo5Jan
l+JtAJ++agJGmJ++agJ: (tringH: *oid
l+JtmCoordinatJG7: intH: *oid
l+JtnCoordinatJGy: intH: *oid
l+JtCJntJrJdG"JntJrJd: Moo5JanH: *oid
lpaintComponJntGg: %raphi"+H: *oid
lgJtOJr6JrrJd(ioJGH: IimJn+ion
lgJtAinim!m(ioJGH: IimJn+ion

1
TJ+tKontAJtri"+


0OanJ5

Y"har toPJn

lgJtToPJn
l+JtToPJn
lpaintComponJt
lmo!+JC5i"PJd

0KramJ

Y"har toPJn

lgJtToPJn
l+JtToPJn
lpaintComponJt
lmo!+JC5i"PJd

1
eg "" hnh hnh ha" trn OanJ5
!
V ung thng
!
V hnh ch nht
!
V hnh bu dc
!
V cung trn
!
V a gic
eg 8Wng thpng
drawLine(x1, y1, x2, y2);
eg hnh "h^ nht
!
drawRect(x, y, w, h);
!
fillRect(x, y, w, h);
eg hnh "h^ nht gS" trqn
!
drawRoundRect(x, y, w, h, aw, ah);
!
fillRoundRect(x, y, w, h, aw, ah);
eg hnh M$! d<"
!
drawOval(x, y, w, h);
!
fillOval(x, y, w, h);
eg "!ng trqn
!
drawArc(x, y, w, h, angle1, angle2);
!
fillArc(x, y, w, h, angle1, angle2);
eg 8a gi"
int[] x = {40, 0, 0, 45, 20};
int[] y = {20, 40, 80, 45, 0};
g.drawPolygon(x, y, x.length);
g.fillPolygon(x, y, x.length);
e d< f,r: eg "hib" 8Eng hE
!
Mc tiu: Su dng cc phung thc v
v luong gic v mt chic ng
h hin thi gi, pht, giy hin tai
trong mt frame.
e d< f,r GtibpH
xEnd = xCenter + handLength
sin()
yEnd = yCenter - handLength
cos()
e 1 phZt "S r0 giyC gS" "`a
Pim giy 5#:
second (2/60)
e d< f,r GtibpH
xEnd = xCenter + handLength
sin()
yEnd = yCenter - handLength
cos()
e9 tr "`a Pim phZt 82" 7" 89nh
M_i phZt *# giy thJo "ng th;"
min!tJ l +J"ondjr0, e d<C nb!
thWi gian 5# \ phZt \0 giy, Tsng
+@ phZt 5# \,k, e 1 giW "S r0
phZtC gS" "`a Pim phZt 5#:
(minute + second/60)
(2/60)
e d< f,r GtibpH
xEnd = xCenter + handLength
sin()
yEnd = yCenter - handLength
cos()
e hnh trqn 82" "hia th#nh 1>
giWC gS" "`a Pim giW 5#:
(hour + minute/60 +
second/(60 60)))
(2/12)
Lp trnh h4ng +i Pin
!
Lp trnh hng th tc
(Procedural programming) chung
trnh uoc thc hin theo th t
thu tc.
!
Trong lp trnh hng s !i"n
(e#ent$dri#en programming), m
lnh uoc thc hin vo lc kch
hoat s kin.
(i Pin
!
Mt s !i"n (e#ent) c th uoc inh
ngha l mt loai tn hiu bo cho
chung trnh c iu g xay ra..
!
S kin uoc sinh ra boi cc hnh ng
cua ngui su dng (v d: di chut,
kch phm chut, n phm) hoac boi
(vd: timer).
C" 54p +i Pin
C" 54p +i Pin trn ntm trong gSi java.awt.event
ring Li+t(J5J"tionV*Jnt _ trong gSi javax.swing.event
(J5J"tJd &+Jr -"tion+
Source Event Type
User Action O!ect Gener"te#
C5i"PJd on a M!tton JButton ActionEvent
ChangJd tJ7t JTextComponent TextEvent
Io!M5JY"5i"PJd on a 5i+t itJm JList ActionEvent
(J5J"tJd or dJ+J5J"tJd an itJm JList ItemEvent
)ith a +ing5J "5i"P
(J5J"tJd or dJ+J5J"tJd an itJm JComboBox ItemEvent
A hnh `y u!yvn
(J5J"tJd V*Jnt Qand5Jr+
Event C$"ss Listener %nter&"ce Listener 'et(o#s )H"n#$ers*
ActionEvent ActionListener actionPerformed(ActionEvent)
ItemEvent ItemListener itemStateChanged(ItemEvent)
WindowEvent WindowListener windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
ContainerEvent ContainerListener componentAdded(ContainerEvent)
componentRemoved(ContainerEvent)
e d< f,w:
mX 5[ +i Pin h#nh 8ng 8n gi=n
!
Mc tiu: in thi 2 nt bm OK v Cancel
trong cua s. Khi kch chut vo mt nt,
mt message uoc hin thi ch ra nt
no uoc kch.
import Na*a,!ti5,Rximport Na*a,a)t,Rximport Na*a,a)t,J*Jnt,Rximport Na*a7,+)ing,Rx
"5a++ %!i y
pri*atJ +tati" 0KramJ 6r z n!55x pri*atJ +tati" 0B!tton Mtn z n!55x
pri*atJ +tati" 0B!tton Mtn1 z n!55x
pri*atJ +tati" 0TJ7tKiJ5d t7t z n!55x pri*atJ +tati" LaMJ5 rJgx
p!M5i" +tati" *oid mainG(tring arg+{|H y
LaMJ5 hi z nJ) LaMJ5G}Qi}Hx LaMJ5 nhap z nJ) LaMJ5G}hap:}Hx
t7t z nJ) 0TJ7tKiJ5dGHx rJg z nJ) LaMJ5G}}Hx
0OanJ5 panJ z nJ) 0OanJ5GnJ) %ridLayo!tG\C>HHx
panJ,addGhiHxpanJ,addGrJgHxpanJ,addGnhapHxpanJ,addGt7tHx
MtnznJ) 0B!ttonG}L?}Hx Mtn,+Jt-"tionCommandG}Mtn}Hx
Mtn,+JtAnJmoni"G?JyV*Jnt,e?~LHx jj(! d!ng phim tat -5tlC
Mtn,add-"tionLi+tJnJrGnJ) B!ttonLi+tJnJrGHHx jj n!t Mtn dang Py 7! 5y +! PiJn
Mtn1 z nJ) 0B!ttonG}Can"J5}Hx jj Tao n!t Can"J5
Mtn1,+Jt-"tionCommandG}Mtn1}Hx
Mtn1,+JtAnJmoni"G?JyV*Jnt,e?~CHx jj(! d!ng phim tat -5tlC
Mtn1,add-"tionLi+tJnJrGnJ) B!ttonLi+tJnJrGHHx jj n!t Mtn1 dang Py 7! 5y +! PiJn
panJ,addGMtnHx panJ,addGMtn1Hx
6r z nJ) 0KramJG}Th! nghiJm}Hx 6r,+JtContJntOanJGpanJHx
6r,+JtIJ6a!5tC5o+JLpJrationG0KramJ,Vm'T~L~CLL(VHx
6r,+Jt(ioJG>00C100Hx 6r,+JtLo"ationG>00C >00Hx 6r,+Jtei+iM5JGtr!JHx

jj m! 5y +! PiJn Phi ng!oi d!ng Mam "h!ot *ao n!t
+tati" "5a++ B!ttonLi+tJnJr imp5JmJnt+ -"tionLi+tJnJr y
p!M5i" *oid a"tionOJr6ormJdG-"tionV*Jnt JH y
(tring )hi"hB!tton z J,gJt-"tionCommandG Hx jj %Jt namJ

i6 G)hi"hB!tton,Ju!a5+G}Mtn}HHy
rJg,+JtTJ7tGt7t,gJtTJ7tGHHx
t7t,+JtTJ7tG}}Hx

J5+Jy
6r,di+po+JGHxjjIong Ph!ng
(y+tJm,J7itG0Hxjj?Jt th!" "h!ong trinh


e d< f,: mX 5[ +i Pin "Xa +s


!
A<" ti!: Ainh haa *i" 7X 5[ +i Pin "Xa +s, BFt
P 54p "on n#o "`a 54p .indo) "S th: tBo ra "" +i
Pin "Xa +s +a!: 8 m_C 8ang 8SngC 8 8SngC 8 82"
P"h hoBtC 8 mFt P"h hoBtC 8 82" th! nh th#nh
Mi:! t2ngC phSng to tr_ 5Bi "Xa +s, Chng trnh
n#y tBo mt 6ramJC 53ng nghJ "" +i Pin "Xa +sC *#
hi:n th9 thng Mo "h ra +i Pin 8ang 7!Ft hin,
import Na*a7,+)ing,Rx
"5a++ %!i1 y
p!M5i" +tati" *oid mainG(tring arg+{ |H y
0KramJ my.indo) z nJ) 0KramJGHx
my.indo),+Jt(ioJG00C\00Hx
0LaMJ5 myLaMJ5 z nJ) 0LaMJ5GQJ55o my )or5dHx
my.indo),gJtContJntOanJGH,addGmyLaMJ5Hx
.indo)IJ+troyJr myLi+tJnJr z nJ) .indo)IJ+troyJrGHx
my.indo),add.indo)Li+tJnJrGmyLi+tJnJrHx
my.indo),+Jtei+iM5JGtr!JHx

import Na*a,a)t,Rx import Na*a,a)t,J*Jnt,Rx


p!M5i" "5a++ .indo)IJ+troyJr J7tJnd+ .indo)-daptJr y
p!M5i" *oid )indo)C5o+ingG.indo)V*Jnt JH y
(y+tJm,J7itG0Hx

JButton
!
Button l mt thnh phn gy ra mt
s kin hnh ng khi uoc kch
chut.
!
Cc constructor cua JButton:
JButton()
JButton(String text)
JButton(String text, Icon icon)
JButton(Icon icon)
C" th!" tnh JButton
!
text
!
icon
!
mnemonic
!
horizontalAlignment
!
verticalAlignment
!
horizontalTextPosition
!
verticalTextPosition
Using Buttons
1p ;ng "" +i Pin JButton
JButton bt = new JButton(OK);
bt.setActionCommand(Left);
bt.addActionListener(new Nghenut());
static class Nghenut implements ActionListener{
public void actionPerformed(ActionEvent e)
{
// Get the button label
String actionCommand = e.getActionCommand();
// Make sure the event source is Left button
if (e.getSource() instanceof JButton)
// Make sure it is the right button
if ("Left".equals(actionCommand))
System.out.println ("Button pressed");
}
JCheckBox
!
%hec! &o' l mt thnh phn cho php
ngui dung bt hay tt mt la chon,
ging nhu 1 cng tc n.
!
Cc constructor:
JCheckBox()
JCheckBox(String text)
JCheckBox(String text, boolean selected)
JCheckBox(Icon icon)
JCheckBox(String text, Icon icon)
JCheckBox(String text,Icon icon,boolean selected)
C" th!" tnh JCheckBox
!
JCheckBox c tt ca cc thuc tnh
trong JButton. Ngoi ta, JCheckBox
c thuc tnh:
selected
!
Using Check Box:
JCheckBox cb = new
JCheckBox(Chon);
if (cb.isSelected()) { . . . }
JRadioButton
!
Cc Radio &utton l s bin i cua cc check
box. Chng thung uoc su dng trong mt nhm khi
m ch c 1 button uoc chon tai mt thi im.
!
Cc constructor:
JRadioButton()
JRadioButton(String text)
JRadioButton(String text, boolean selected)
JRadioButton(Icon icon)
JRadioButton(String text, Icon icon)
JRadioButton(String text, Icon icon, boolean selected)
C" th!" tnh JRadioButton
JRadioButton c tt ca cc thuc tnh
trong JButton. Ngoi ra, JRadioButton
c thuc tnh:
selected
%p nhSm "" Radio Button
ButtonGroup btg = new ButtonGroup();
btg.add(jrb1);
btg.add(jrb2);
&+ing Tadio B!tton+:
JRadioButton rb1 = new JRadioButton(Chon);
JRadioButton rb2 = new JRadioButton(Khong
chon);
btg.add(rb1); btg.add(rb2);
if (rb1.isSelected()) { . . . }
JLae!
!
Label dng 8: hi:n th9 mt "h!hi *Dn M=n thng thWng
nhtm m t= thm thng tin "ho "" 8@i t2ng Ph",
!
C" "on+tr!"tor "`a 0LaMJ5:
JLabel()
JLabel(String text)
JLabel(String text,int hAlignment)
JLabel(Icon icon)
JLabel(Icon icon, int hAlignment)
JLabel(String text,Icon icon,int hAlignment)
C"c thu#c t$nh JLae!
!
text
!
icon
!
horizontalAlignment
!
verticalAlignment
Using Labels
J%ext&ie!d
!
Text field l nhp d liu dang van
ban trn 1 dng.
!
Cc constructor cua JTextField:
JTextField()
JTextField(int columns)
Tao mt text field trng c s ct xc inh.
JTextField(String text)
Tao mt text field vi van ban c sn.
JTextField(String text, int columns)
Tao mt text field vi van ban c sn v s
ct xc inh.
C" th!" tnh J%ext&ie!d
!
text
!
horizontalAlignment
!
editable
!
columns
C" phng th;" J%ext&ie!d
!
getText()
Tra v chui k t trong text field.
!
setText(String text)
at chui k t trong text field.
!
setEditable(boolean editable)
Cho php hoac v hiu ha soan thao trong
text field. Mac inh, editable l true.
!
setColumns(int)
Thit lp s ct trong text field. Chiu
di cua text field c th thay i.
J%ext'rea
!
TextArea l khung cho php ngui su
dng nhp vo nhiu dng van ban.
!
Cc constructor cua JTextArea:
JTextArea()
JTextArea(String s)
JTextArea(int rows, int columns)
JTextArea(String s, int rows, int columns)
C" th!" tnh J%ext'rea
!
text
!
editable
!
columns
!
lineWrap
!
wrapStyleWord
!
rows
!
lineCount
!
tabSize
(X d<ng %ext 'rea
Chung trnh hin thi 1 anh v 1 title trong
1 label, hin thi van ban trong text area.
IJ+"riptionOanJ5
YN5M5'magJ
YN5M5Tit5J
YNtaTJ7tIJ+"ription
l+Jt'magJ'"on
l+JtTit5J
l+JtTJ7tIJ+"ription
lgJtAinim!m(ioJ
1
1
TJ7t-rJaIJmo
0OanJ5
Y"har toPJn
lgJtToPJn
l+JtToPJn
lpaintComponJt
lmo!+JC5i"PJd
0KramJ
Y"har toPJn
lgJtToPJn
l+JtToPJn
lpaintComponJt
lmo!+JC5i"PJd
JComoBox
!
%om&o &o' l danh sch n gian cc mc
chon. C ban n thc hin chc nang ging
nhu 1 list, nhung ch c th ly 1 gi
tri.
!
Cc constructor:
JComboBox()
tao 1 combo box rng
JComboBox(Object[] stringItems)
tao 1 combo box cha cc phn tu
trong dy
C" phng th;" JComoBox
jcbo.addItem(Object item)
thm 1 mc chon vo JComboBox jcbo
jcbo.getItem()
jcbo.getItemAt(int index)
ly 1 mc chon tu JComboBox jcbo
jcbo.removeItemAt(int index)
loai 1 mc chon khoi JComboBox jcbo
Using Combo Box:
(X d<ng item(tateChanged Handler
?hi mt 5ia "han 82" "hJ"P ho]" !n"hJ"PC
itemStateChanged() "ho ItemEvent *#
actionPerformed() hand5Jr "ho ActionEvent
+g 82" gai,
public void itemStateChanged(ItemEvent e){
// Make sure the source is a combo box
if (e.getSource() instanceof JComboBox)
String s = (String)e.getItem();
}
JLi)t
!
List l mt thnh phn c ban thc hin
chc nang ging combo box, nhung n cho
php ngui su dng chon mt hoac nhiu gi
tri.
!
Cc constructor:
JList()
tao 1 list rng.
JList(Object[] stringItems)
tao 1 list cha cc phn tu trong dy.
C" th!" tnh JLi)t
!
selectedIndex
!
selectedIndices
!
selectedValue
!
selectedValues
!
selectionMode
!
visibleRowCount
Using Lists:
J(cro!!Bar
!
(crollBar l mt iu khin cho php
ngui su dng chon tu mt dai cc gi
tri.
!
Cc constructor:
JScrollBar()
JScrollBar(int orientation)
JScrollBar(int orientation, int value,
int extent, int min, int max)
C" th!" tnh J(cro!!Bar
!
orientation: 1 - doc, 0 - ngang
!
maximum, minimum
!
visibleAmount (extent): rng cua phn
con chay
!
value: gi tri hin thi cua scroll bar
!
blockIncrement: gi tri uoc cng thm
khi kch hoat vung tang.
!
unitIncrement: gi tri uoc cng thm khi
kch hoat u tang.
C" phng th;" J(cro!!Bar
!
setBlockIncrement(int increment)
!
setMaximum(int maximum)
!
setMinimum
!
setOrientation(int orientation)
!
setUnitIncrement(int increment)
!
setValue(int value)
!
setVisibleAmount (extent):
!
getBlockIncrement()
!
...
Borders
!
Ban c th thit lp mt border trn bt
ky i tuong no cua lp JComponent, nhung
thung hu ch khi thit lp mt titled
border trn JPanel nhm mt tp cc thnh
phn giao din ngui su dng c lin quan.
!
Using border:
C" phng th;" tnh 8: tBo Borders
!
createTitledBorder(String title)
!
createLoweredBevelBorder()
!
createRaisedBevelBorder()
!
createLineBorder(Color color)
!
createLineBorder(Color color, int thickness)
!
createEtchedBorder()
!
createEtchedBorder(Color highlight,
Color shadow, boolean selected)
!
createEmptyBorder()
!
createMatteBorder(int top, int left,
int bottom, int right, Icon tileIcon)
!
createCompoundBorder(Border outsideBorder,
Border insideBorder)
Dialogs
!
C th su dng lp JOptionPane
tao 4 loai dialog chun:
/
Message Dialog hi:n th9 mt mJ++agJ *# 82i ngWi +X
d<ng P"h nZt L? 8: 8Sng hp thoBi,
/
Confirmation Dialog hi:n th9 "! hi *# 8v ngh9 ngWi
+X d<ng tr= 5WiC *d: L? hay Can"J5
/
Input Dialog hi:n th9 "! hi *# nhn d^ 5i! *#o t 1 tJ7t
6iJ5dC "omMo Mo7 ho]" 5i+t,
/
Option Dialog hi:n th9 "! hi *# nhn "! tr= 5Wi t mt
tp "" 5ia "han,
TBo "" Message Dialog
Su dng phung thc tnh trong lp
JOptionPane
showMessageDialog(Component parentComponent,
Object message)
showMessageDialog(Component parentComponent, Object
message,String title, int messageType)
showMessageDialog(Component parentComponent,
Object message, String title,
int messageType, Icon icon)

TBo "" Confirmation Dialog
Su dng phung thc tnh trong lp
JOptionPane
showConfirmDialog(Component parentComponent,
Object message)
showConfirmDialog(Component parentComponent, Object
message, String title, int optionType)
showConfirmDialog(Component parentComponent, Object
message, String title, int optionType,
[[int messageType], Icon icon])

TBo "" Option Dialog
Su dng phung thc tnh trong lp
JOptionPane
showOptionDialog(Component parentComponent, Object
message, String title, int optionType, int
messageType, Icon icon, Object[] options, Object
initialValue)
Su dng cc dialog:
Menus
!
Java cung cp mt s lp - JMenuBar,
JMenu, JMenuItem, JCheckBoxMenuItem, v
JRadioButtonMenuItem - thc thi menu
trong mt frame.
!
Mt JFrame hoac JApplet c th cha mt
menu &ar trn c gn cc pull$do)n
menu. Cc menu cha cc menu item
ngui dung la chon (hoac bt/tt).
Menu bar c th uoc xem nhu mt cu
trc h tro cc menu.
Menu Demo
L4p J*enuBar
Menu bar "h;a "" mJn!x mJn! Mar "h "S th: 82"
thm *#o 1 6ramJ, 1oBn "odJ +a! tBo *# thm mt
0AJn!Bar *#o 1 6ramJ:
JFrame f = new JFrame();
f.setSize(300, 200);
f.setVisible(true);
JMenuBar mb = new JMenuBar();
f.setJMenuBar(mb);
L4p *enu
BBn g3n "" mJn! *#o mt JMenuBar, 1oBn "odJ
+a! tBo > mJn! File *# elpC *# thm "hZng *#o
JMenuBar mb:
JMenu fileMenu = new JMenu("File", false);
JMenu helpMenu = new JMenu("elp", true);
mb.add(fileMenu);
mb.add(helpMenu);
L4p J*enu+tem
1oBn "odJ +a! thm "" m<" "han GmJn! itJmH *# ""
+Jparator trong mJn! fileMenu:
fileMenu.add(new JMenuItem("New"));
fileMenu.add(new JMenuItem("Open"));
fileMenu.addSeparator();
fileMenu.add(new JMenuItem("Print"));
fileMenu.addSeparator();
fileMenu.add(new JMenuItem("Exit"));
Submenus
BBn "S th: thm "" +!MmJn!+ *#o "" mJn! itJm, 1oBn
"odJ +a! thm "" +!MmJn! &ni7C TC *# .infk *#o
trong m<" "han (o6t)arJ,
JMenu softwareelpSubMenu = new JMenu("Software");
JMenu hardwareelpSubMenu = new JMenu("ardware");
helpMenu.add(softwareelpSubMenu);
helpMenu.add(hardwareelpSubMenu);
softwareelpSubMenu.add(new JMenuItem("Unix"));
softwareelpSubMenu.add(new JMenuItem("NT"));
softwareelpSubMenu.add(new JMenuItem("Win5"));
Submenu Demo
(X d<ng Menu
Tao mt giao din thc hin cc php
ton s hoc gia 2 s Number1 v
Number2. Giao din cha cc nhn v
text field cho Number 1, Number 2,
v Result (su dng nhu i vi
JButton).
B4" 1: TBo 1 +!M"5a++ "`a 54p JFrame G82" gai
5# 1 SubFrameH 8: 7" 89nh "Xa +s m4i 5#m *i"
g, e d<C tFt "= "" "hng trnh ;ng d<ng %&' m_
rng JFrame *# 5# "" +!M"5a++ "`a JFrame,
TBo thm Window Y M4" 1
TBo thm Window Y M4" >
Buc 2: Tao 1 instance cua SubFrame
trong ng dng hoac trong applet.
V d:
SubFrame subFrame = new
SubFrame("SubFrame Title");
TBo thm Window Y M4" \
Buc 3: Tao 1 JButton kch hoat
subFrame.
add(new JButton("Activate SubFrame"));
TBo thm Window Y M4"
Buc 4: chng phung thc actionPerformed() nhu
sau:
public actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (e.target instanceof Button)
{
if ("Activate
SubFrame".equals(actionCommand))
{
subFrame.setVisible(true);
}
}
}
e d<: TBo nhiv! Window
V d tao 1 main window c 1 text area
trong scroll pane, 1 button "Show
istogram". Khi ngui su dng kch vo
button, 1 cua s mi xut hin hin
thi biu cho biu din tn s xut
hin cua cc k t trong text area.
J(cro!!Pane
Scroll pane l mt thnh phn t
ng h tro cun cua s m khng cn
lp trnh.
Using Scroll Pane: add mt TextArea
vo trong mt Scroll pane
CF! trZ" Scroll Pane
Co5!mn hJadJr CornJr
ComponJnt
To) hJadJr
0eiJ)port
("ro55aM5J ComponJnt
Qorioonta5 +"ro55 Mar+
eJrti"a5 +"ro55 Mar+
CornJr
ComponJnt
CornJr
ComponJnt
CornJr
ComponJnt
J%aedPane
Tabbed pane cung cp mt tp cc tab loai
tru ln nhau truy nhp nhiu thnh
phn.
Using Tabbed Pane:

You might also like