You are on page 1of 442

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

Bi 1. Tng quan lp trnh Java


Gii thiu ngn ng Java Kin trc ca Java Ni dung mt chng trnh Java c bn Cc kiu d liu c bn & ton t Cc cu trc iu khin Nhp d liu t bn phm Cng c son tho Bi tp
2

Gii thiu ngn ng Java


Lch s pht trin ca Java
Ra i ti Sun Microsystems bi James Gosling 1991: Version u tin vi tn Oak 1995: Tn chnh thc l Java

Mc ch ca Java
Dng pht trin ng dng cho cc thit b in t thng minh To cc trang web c ni dung ng (web applet) Hin nay, Java c s dng pht trin nhiu loi ng dng khc nhau: c s d liu, mng, Internet, vin thng...
3

Gii thiu ngn ng Java


c im ca Java
n gin Hng i tng a nhim An ton Garbage Collection My o (bin dch v thng dch) Kh chuyn (Portability) Phn tn
4

Kin trc ca Java


Java Platform
Java Virtual Machine (Java VM) Java Application Programming Interface (Java API)
myProgram.java

M ngun

Java API Java VM Hardware-Platform

Java Platform

Kin trc ca Java


Java Development Kit JDK
B cng c pht trin Java (jdk) gm trnh bin dch, thng dch, tr gip, son ti liu v cc th vin chun Ngoi ra cn mt s th vin khc nh JSP, JavaMail, Java TAPI 1995: Version JDK 1.0 1998: Version JDK 1.2 (Java 2nd Platform) 2004: Version JDK 1.5

Pht trin ng dng Java


Hai loi ng dng Java
Application: ng dng c lp Applet: ng dng chy trn Web

Th vin lp Java
B JDK bao gm rt nhiu lp chun c xy dng sn. Lp trnh vin thng s dng cc lp chun pht trin ng dng.

Pht trin ng dng Java


Cc bc pht trin
Hello.java
public class Hello { public static }

java Hello 01001011

Thng dch

Bin dch
javac Hello.java

---------------------------------------------------------------

Hello.class (bytecode)
8

Mt chng trnh Java c bn


1 2 3 4 5 6 7 8 9 10 11 12 13 // Tn file : Hello.java /* Tc gi : Cao c Thng*/

Tn lp cha hm main phi ging tn file

public class Hello { // Phng thc main, im bt u ca chng trnh public static void main( String args[ ] ) im bt u v kt thc ca lp { System.out.println( Hello World" ); Du hiu ch thch => } // Kt thc phng thc main } // Kt thc lp Hello

Khai bo lp

Mi CT phi c t nht mt khai bo lp

Lm cho chng trnh d hiu hn. Trnh bin dch s b qua nhng dng c du ch thch Phng thc main() s c gi u tin. Mi CT thc thi phi c mt phng thc main()

Hin th dy k t ra mn hnh

9y Cc cu lnh phi kt thc bng du chm ph

Mt chng trnh Java c bn


Bin dch chng trnh
Vo ch Console ca Windows G cu lnh javac Hello.java Nu khng c thng bo li, file Hello.class s c to ra

Thc thi chng trnh


G cu lnh java Hello (khng cn .class)

10

Mt chng trnh Java c bn


Thay i cch hin th
public class Hello { public static void main(String args[]) { System.out.print( Chao\tmung\nban\nden\tvoi\nlap trinh Java\n" ); } }
Chao mung ban den voi lap trinh Java

11

Cc kiu d liu c bn
Java c hai kiu d liu
D liu gc chun: L cc kiu d liu c nh ngha trong ngn ng nh s nguyn, s thc, k t, logic D liu dn xut: Do ngi dng t nh ngha nh mng, lp, giao tip

V d khai bo bin
int x; Person ps;
12

Cc kiu d liu c bn
Kiu s nguyn
Kiu byte short int long Kch thc Khong gi tr 8 bits 16 bits 32 bits 64 bits -256255 -3276832767 -232232 1 -264264 1

Kiu s thc
Kiu float double Kch thc Khong gi tr 32 bits 64 bits -3.4e383.4e38 -1.7e3081.7e308
13

Cc kiu d liu c bn
Kiu boolean: Nhn gi tr true hoc false Kiu char: Kiu k t theo chun Unicode
Mt s hng k t Hng \uxxxx \t \n \r \ ngha K t Unicode Tab ngang Xung hng Du enter Nhy n
14

Cc kiu d liu c bn
Kiu mng
Khai bo: int[] iarray; hoc int iarray[]; Cp pht: iarray = new int[100]; Khi to:
int[] iarray = {1, 2, 3, 5, 6}; char[] carray = {a, b, c}; Ch : Lun khi to hoc cp pht mng trc khi s dng

Mt s khai bo khng hp l:
int[5] iarray; int iarray[5];
15

Cc kiu d liu c bn
Kiu mng
Truy cp mng
iarray[3] = 0; carray[1] = z; Ch : Ch s ca mng c tnh t 0

Ly s phn t mng: iarray.length

16

Cc kiu d liu c bn
Quy tc t tn bin
Bt u bng mt ch ci, mt du gch di (_) hoc mt du dollard ($) Khng c khong trng gia tn Sau k t u c th dng k t, s, du dollard, du gch di Khng trng vi cc t kho V d: a_1234_d, 1awas, _asdc, a sas, $erd, %ats
Ch : Java phn bit ch hoa ch thng
17

Cc ton t
Bng ton t
= ?: && ^ += |= >>>= > == || * % -= ^= < <= ++ / << *= %= ! >= -& >> /= <<= ~ != + | >>> &= >>=

18

Cc cu trc iu khin
Lnh if/else
import java.util.Date; public class TestIf { public static void main( String args[ ] ) { Date today = new Date(); if( today.getDay() == 0 ) System.out.println(Hom nay la chu nhat\n); else System.out.println(Hom nay khong la chu nhat\n" ); } }

19

Cc cu trc iu khin
Lnh switch
import javax.swing.JOptionPane; public class TestSwitch { public static void main(String[] args) { char c; String str=JOptionPane.showInputDialog(null,"Nhap vao ky tu?"); c = str.charAt(0);

20

Cc cu trc iu khin
Lnh switch
switch(c) { case 'a': case 'e': case 'i': case 'o': case 'u': System.out.println("Ky tu nay la nguyen am"); break; default: System.out.println("Ky tu nay la phu am"); } System.exit(0); // kt thc chng trnh } }

21

Cc cu trc iu khin
Vng lp for
for(<khi to>; <iu kin lp>; <bc nhy>) <khi lnh>;
// Chng trnh tnh tng cc s l t 1 n 100 public class TestFor { public static void main(String[] args) { int tong = 0; for(int i=1; i<=100; i+=2) tong+=i; System.out.println(tong); } }

22

Cc cu trc iu khin
Vng lp while
while (<biu thc boolean>)
<khi lnh>;
// Tnh tng cc s l t 1 n 100 int tong = 0, i = 1; while (i<=100) { tong+=i; i+=2; } System.out.println(tong);

23

Cc cu trc iu khin
Vng lp do/while
do { <khi lnh>; } while <biu thc boolean>;
// Tnh tng cc s l t 1 n 100 int tong = 0, i=1; do { tong+=i; i+=2; } while (i<=100); System.out.println(tong);
24

Nhp d liu t bn phm


V d nhp mt s nguyn v mt s thc
import java.io.*; public class TestInput { public static void main(String[] args) throws Exception { BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Nhap mot so nguyen:"); String siNumber = inStream.readLine(); int iNumber = Integer.parseInt(siNumber);

25

Nhp d liu t bn phm


System.out.print("Nhap mot so thuc:"); String sfNumber = inStream.readLine(); float fNumber = Float.parseFloat(sfNumber); System.out.println("So nguyen: + iNumber); System.out.println("So thuc: + fNumber); } }

26

V d: Xy dng i tng Circle


Cch 1: S dng mt file Circle.java duy nht
public class Circle { private int radius;

public Circle(int r) { radius = r; } public double getArea() { return Math.PI*radius*radius; } public double getCircum() { return 2*Math.PI*radius; }

public static void main(String[] args) { Circle c = new Circle(5); System.out.println("Area = " + c.getArea()); System.out.println("Circumference = " + c.getCircum()); } }
27

V d v i tng Circle
Cch 2: S dng mt file vi 2 lp ring bit
public class TestCircle { public static void main(String[] args) { Circle c = new Circle(5); System.out.println("Area = " + c.getArea()); System.out.println("Circumference = " + c.getCircum()); } } class Circle { ... }

28

V d v i tng Circle
Cch 3: S dng hai file ring bit
// file TestCircle.java public class TestCircle { public static void main(String[] args) { ... } } // file Circle.java class Circle { ... }

29

Cng c son tho


Notepad Jbuilder Eclipse EditPlus JCreator

30

Ch dn thc hnh
t bin mi trng PATH:
Trong Windows: Nhy phi trn My Computer, chn Properties, chn Advanced, chn Enviroment Variables, chn bin PATH v edit, thm vo ng dn ti th mc bin ca b JDK. Trong ch Console: G lnh set Path=%Path%;ng dn ti bin

Nn tham kho java/docs khi lm vic


31

Bi tp
1. Vit chng trnh tnh tin in thoi:
Tin thu bao hng thng l 27000 . T pht gi th nht n pht th 200 gi cc l 120 /pht. T pht gi th 201 n pht th 400 gi cc l 80 /pht. T pht gi 401 n pht cui gi cc l 40 /pht.

32

Bi tp
2. Vit chng trnh gii phng trnh bc hai ax2 + bx + c = 0 vi a,b,c nhp t bn phm. 3. Vit chng trnh nhp vo mt dy cc s nguyn khc 0, kt thc nhp khi gp s 0. Sau tnh trung bnh cng ca dy s . Tm s ln nht, s nh nht ca dy s. 4. Vit chng trnh tnh tng E = 1 + 1/1 + 1/2 + 1/3 + + 1/n vi n nhp vo t bn phm
33

Bi tp
5. M rng lp Circle : thm d liu to tm hnh trn v phng thc kim tra mt im cho trc c nm trong hnh trn hay khng. 6. Vit chng trnh nhp vo mt hnh trn, sau pht sinh 100 im ngu nhin v cho bit c bao nhiu im nm trong hnh trn va nhp.

34

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

Bi 2. OOP trong Java


Cc phng php lp trnh Gii thiu v OOP K tha (Inheritance) a hnh (Polymorphism) Giao tip (Interface) Lp tru tng (Abstract) Gi (Packages) Java vs C++ Bi tp
2

Cc phng php lp trnh


Step-by-Step Programming
Lp trnh tng bc Machine Language, Assembly Language
1101011100111101 1010000111011101 0110111011001010 1000100100101011 ... MOV BX, CS SUB BX, 10h JNE label1 LOOP label2 ...

Cc phng php lp trnh


Procedural Programming
Thit k top-down. Chng trnh c chia thnh cc hm, th tc. Pascal, C Hn ch: dng d liu ton cc, kh pht trin, kh m t cc thc th trong thc t
Program

Proc1

Proc3

Proc2

Cc phng php lp trnh


Object-Oriented Programming
Chng trnh bao gm cc i tng. Cc i tng tng tc vi nhau thng qua cc phng thc ca chng D m t cc thc th D pht trin, m rng chng trnh
Object A

Object B

Object C

Object D

Lp trnh hng i tng-OOP


Lp v i tng
D liu v cc thao tc trn d liu c kt hp trong cng mt i tng (object) Lp (class) nh ngha cc tnh cht ca mt tp hp cc i tng cng kiu i tng l cc th hin (instances) ca lp

c im ca OOP
Tnh ng gi (Encapsulation) Tnh k tha (Inheritance) Tnh a hnh (Polymorphism)
6

V d v OOP trong Java


Lp Time v TimeTest nm trong cng th mc Lp Time nm trong file Time.java. N cha cc nh ngha v thi gian. Lp TimeTest nm trong file TimeTest.java. N dng kim tra lp Time. Lp TimeTest cha hm main. Khi chy ch cn g: javac TimeTest.java java TimeTest Java s t ng tm v dch file Time.java
7

Lp Time
// File Time.java import java.text.DecimalFormat; public class Time { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 // Cau tu public Time() { setTime( 0, 0, 0 ); } // Ham thiet lap du lieu public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); }

Lp Time
// Chuyen sang khuon dang thoi gian quoc te public String toUniversalString() { DecimalFormat twoDigits = new DecimalFormat( "00" ); return twoDigits.format( hour ) + ":" + twoDigits.format( minute ) + ":" + twoDigits.format( second ); } // Chuyen sang khuon dang thoi gian thong thuong public String toStandardString() { DecimalFormat twoDigits = new DecimalFormat( "00" ); return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + ":" + twoDigits.format( minute ) + ":" + twoDigits.format( second ) + ( hour < 12 ? " AM" : " PM" ); } 9 } // Ket thuc lop Time

Lp Time
D liu
Mi d liu phi c mt phm vi nht nh

Phng thc
Cu t c tn trng vi tn lp Cu t khng c kiu tr v C th c nhiu cu t (overloading) Mi phng thc phi c mt phm vi nht nh

10

Lp TimeTest
// File TimeTest.java import javax.swing.JOptionPane; public class TimeTest { public static void main( String args[ ] ) { Time time = new Time(); // Tao mot doi tuong kieu Time // Lay thoi gian String output = "The initial universal time is: " + time.toUniversalString() + "\nThe initial standard time is: + time.toStandardString(); // Dat lai thoi gian time.setTime( 13, 27, 6 ); output += "\n\nUniversal time after setTime is: " + time.toUniversalString() + "\nStandard time after setTime is: " + time.toStandardString();

11

Lp TimeTest
// Dat lai thoi gian time.setTime( 99, 99, 99 ); output += "\n\nAfter attempting invalid settings: " + "\nUniversal time: " + time.toUniversalString() + "\nStandard time: " + time.toStandardString(); JOptionPane.showMessageDialog( null, output, "Testing Class Time1", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // Ket thuc ham main } // Ket thuc lop TimeTest

12

Chy TimeTest
javac TimeTest.java java TimeTest

13

Phm vi truy cp
private
Ch truy cp c t trong lp khai bo.

protected
Truy cp c t trong lp khai bo, lp con ca ca lp khai bo v cc lp cng gi vi lp khai bo.

public
Truy cp c t mi ni.

Mc nh
Truy cp c t trong lp khai bo v cc lp cng gi vi lp khai bo.
14

T kho this
T kho this ch i tng hin thi
public class Time { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 // Viet lai ham setTime public void setTime( int hour, int minute, int second ) { this.hour = ( ( hour >= 0 && hour < 24 ) ? hour : 0 ); this.minute = ( ( minute >= 0 && minute < 60 ) ? minute : 0 ); this.second = ( ( second >= 0 && second < 60 ) ? second : 0 ); }
15

Np chng hm khi to
// Ham khoi tao khong tham so public Time() { this( 0, 0, 0 ); } // Ham khoi tao mot tham so public Time( int h ) { this( h, 0, 0 ); } // Ham khoi tao hai tham so public Time( int h, int m ) { this( h, m, 0 ); } // Ham khoi tao ba tham so public Time( int h, int m, int s ) { setTime( h, m, s ); } // Ham sao chep public Time( Time time ) { this( time.hour, time.minute, time.second ); } // Su dung cac cau tu Time t1 = new Time(); // 00:00:00 Time t2 = new Time( 2 ); // 02:00:00 Time t3 = new Time( 21, 34 ); // 21:34:00 Time t4 = new Time( 12, 25, 42 ); // 12:25:42 Time t5 = new Time( 27, 74, 99 ); // 00:00:00 Time t6 = new Time( t4 ); // 12:25:42
16

Mt s t kho
T kho final
p dng cho lp, phng thc, bin. Lp final: l lp khng th c lp con public final class NoChild {...} Bin final: l bin khng th thay i khi gn gi tr private final int MAX = 100; Phng thc final: l phng thc khng th np chng public final void NoOverride();
17

Mt s t kho
T kho static
c dng vi phng thc v bin. Bin static: l bin chung cho mi i tng ca lp, n c truy cp qua i tng ca lp hoc qua tn lp. private static char TAB = \t; Phng thc static: l phng thc ch c php truy cp ti cc bin static ca lp, n c th gi ngay c khi cha c i tng no ca lp. public static void Welcome() {...}
18

K tha (Inheritance)
K tha l vic xy dng lp mi da trn lp c sn
Lp c sn l lp cha: superclass Lp mi l lp con: subclass

V d:
Hnh vung k tha t hnh ch nht Con ch k tha t loi ng vt di nc

Ch :
Tnh k tha th hin quan h is a, khc vi quan h has a (composition) Composition: mt i tng cha cc i tng thuc lp khc. V d: t c cc bnh xe
19

Cy k tha

Animal

TerrestrialAnimal

AquaticAnimal

Cat

Horse

Chicken

Fish

Octopus

20

V d v k tha trong Java


Xy dng lp Hnh cu (Sphere) k tha t lp Hnh trn (Circle)
// File Circle.java public class Circle { protected int radius; // radius co the duoc truy cap tu Sphere public Circle( int radius ) { this.radius = radius; } public int getRadius() { return radius; } public double getArea() { return Math.PI*radius*radius; } public double getCircum() { return 2*Math.PI*radius; }

21

V d v k tha trong Java


// File Sphere.java Sphere k tha t Circle public class Sphere extends Circle { public Sphere( int radius ) { super(radius); // Goi cau tu cua lop cha } // Ham tinh dien tich bet mat. Nap chong ham getArea() public double getArea() { return 4*Math.PI*radius*radius; } // Ham tinh the tich public double getVolume() { return (4.0d/3)*Math.PI*radius*radius*radius; } }
22

V d v k tha trong Java


// File InheritanceTest.java public class InheritanceTest { public static void main(String[] args) { Circle circle = new Circle(5); Sphere sphere = new Sphere(2); System.out.println(Radius of circle: " + circle.getRadius()); System.out.println("Radius of sphere: " + sphere.getRadius()); System.out.println("Area of circle: " + circle.getArea()); System.out.println(Area of sphere: " + sphere.getArea()); System.out.println("Volume of sphere: " + sphere.getVolume()); } }
23

T kho super
T kho super ch i tng ca lp cha
super(radius): Gi cu t ca lp cha

Question: Thm phng thc tnh din tch mt ct qua tm hnh cu ? Answer: chnh l din tch hnh trn
// Them phuong thuc nay trong lop Sphere public double getAreaCut() { return super.getArea(); } // ... // Ham main, goi Tinh dien tich mat cat System.out.println(Area cut of sphere: " + sphere.getAreaCut()); // ...
24

a hnh (Polymorphism)
V d:
class A { public void method() { System.out.println(method of A); } } class B extends A { public void method() { System.out.println(method of B); } } class C extends A { public void method() { System.out.println(method of C); } } // Cu lnh trong main A a = new A(); a.method(); a = new B(); a.method(); C c = new C(); a = c; a.method(); // Kt qu mn hnh method of A method of B method of C
25

a hnh (Polymorphism)
Tnh a hnh th hin qua vic: cng mt phng thc nhng c ni dung thc hin khc nhau trn cc i tng khc nhau. Phng thc gi c xc nh thng qua i tng c tham chiu, khng thng qua kiu khai bo ca tham chiu. Trong Java, cc phng thc lun mang tnh a hnh.

26

Lp tru tng (abstract)


Lp tru tng ch c dng lm lp cha cho cc lp khc, n khng c cc th hin (instance). Lp tru tng nh ngha cc thuc tnh chung cho cc lp con ca n. V d c th thit k lp Hnh trn, Hnh vung... k tha t lp tru tng Hnh. Lp Hnh c thuc tnh l tn hnh, cc phng thc tnh din tch, chu vi...

27

Lp tru tng
Lp tru tng (abstract) thng c t nht mt phng thc tru tng, l phng thc khng c ci t.
public abstract void draw();

Khai bo lp tru tng


public abstract class ClassName {}

Cc lp con ca mt lp cha tru tng phi ci t tt c cc phng thc tru tng. Nu khng n cng s tr thnh lp tru tng. Khng th to cc i tng ca mt lp tru tng nhng c th khai bo bin thuc kiu lp tru tng tham chiu n cc i tng thuc lp con ca n.
28

Lp tru tng
public abstract class Shape { static final double PI = 3.14159; public abstract double getArea(); public abstract double getVolume(); } class Circle extends Shape { double radius; public double getArea() { return PI*radius*radius; } public double getVolume() { return 0; } } class Cube extends Shape { double a, b, c; public double getArea() { return 2*(a*b+b*c+c*a); } public double getVolume() { return a*b*c; } }
29

Giao tip (interface)


Giao din ch ra cc tnh cht m mt i tng c th c, trong mt ng cnh no .
Mt ngi c th khi nh l mt ngi con, trng l mt sinh vin, lp l mt ngi bn.

Giao din trong Java c th c dng th hin s a k tha nh trong C++.

30

Giao tip (interface)


Khai bo giao tip
interface Name {...}

Mt giao tip thng ch cha cc hng static v cc phng thc public cha ci t. Mt giao tip c th tha k mt giao tip khc. Mt lp c th ci t (implements) mt hay nhiu giao tip nhng ch c th tha k (extends) t mt lp.

31

Giao tip (interface)


interface Drawable { public void draw(); } public abstract class Shape {...} public class Circle extends Shape implements Drawable { ... public void draw() {...} }

32

Gi (package)
Package cho php nhm mt tp hp cc lp hoc cc giao tip c quan h vi nhau d dng qun l, bo tr, phn phi V d: To package Transport cha cc lp v phng tin i li: Car, Moto, Boat... t cc lp vo cng th mc Transport Khai bo u mi lp dng

package Transport;

33

Gi (package)
S dng package cch 1: Khai bo import
V d 1: import V d 2: import V d 3: import Point p Transport.Car; Transport.*; java.awt.Point; = new Point(1,2);

S dng package cch 2: S dng trc tip


java.awt.Point p = new java.awt.Point(1,2); javax.swing.JOptionPane.showMessageDialog(...);

Ch :
Ch c th truy cp c n cc lp public trong cc package Package java.lang.* c t ng import vo mi chng trnh
34

Java vs C++
1. 2. Mt chng trnh Java chy chm hn so vi mt chng trnh C tng ng khong 20 ln. Java khng c kiu lit k (enum), kiu cu trc (struct) hay hp (union), n ch c class. Mi bin hay hm ca Java u nm trong mt class no . Java khng c ton t phm vi (scope) :: C ca cc kiu d liu nguyn thu (primitive) trong Java khng ph thuc vo my. c bit kiu char c c 16 bit (Unicode). Biu thc logic trong Java ch nhn gi tr boolean. Trong Java, mi bin khng thuc kiu nguyn thu u phi to ra bng t kho new. Java khng c tin x l (preprocessor)
35

3. 4.

5. 6. 7.

Java vs C++
8. 9. 10. 11. 12. 13. 14. 15. Java khng c con tr. Java khng c hu t (destructor), n ch c phng thc finalize() c gi bi Garbage Collector. Java khng h tr i s mc nh. Java ch h tr k tha n, tt c mi lp u mc nh k tha t lp Object. Java khng c template. Java khng c t kho virtual. Tt c mi phng thc non-static u lun dng dynamic binding. Java khng c qu ti ton t (operator overloading). i s ca hm lun c x l nh i s gi tr (value argument)
36

Bi tp
1. Ci t li cc ni dung l thuyt hc. 2. Xy dng lp Candidate (Th sinh) gm cc thuc tnh: m, tn, ngy thng nm sinh, im thi Ton, Vn, Anh v cc phng thc cn thit. 3. Xy dng lp TestCandidate kim tra lp trn:
Nhp vo 10 th sinh In ra thng tin v cc th sinh c tng im ln hn 15

37

Bi tp
4. Xy dng lp Point c d liu l 2 to x,y v cc phng thc cn thit. Thm phng thc toString tr v mt String c dng [x, y]. 5. Xy dng lp Rect c d liu l im trn tri v di phi. Qu ti cc cu t cung cp nhiu cch khi to. Thm cc phng thc: Kim tra 1 im c nm trong hnh ch nht hay khng. Tnh giao ca 2 hnh ch nht.
38

Bi tp
6. Xy dng lp TestRect: Sinh ngu nhin 10 hnh ch nht v tnh giao i mt ca chng. 7. Xy dng lp Triangular c 3 phng thc static tnh din tch tam gic theo 3 cch khc nhau: cnh y v chiu cao, cng thc Heron, di 2 cnh v gc.

39

Bi tp
8. Xy dng lp Employee c name v phng thc tru tng l earnings(). Xy dng lp Boss k tha t Employee c cch tnh lng l mt khon c nh hng thng. Xy dng lp PieceWorker c cch tnh lng da trn s sn phm lm c, lng mt sn phm l $ 0.5. Xy dng lp CommissionWorker c cch tnh lng l mt khon c nh + tin hoa hng trn s sn phm bn c, mi sn phm c $ 0.1 hoa hng.
40

Bi tp
9. Xy dng lp tru tng Animal c d liu l name v weight, phng thc o l grow (tng trng lng). 10.Xy dng lp Chicken k tha t Animal, ci t phng thc o mi ln grow th trng lng tng 0.3 kg. Xy dng lp Sparrow k tha t Animal, mi ln tng trng lng 0.05 kg. 11.Xy dng giao din Flyable c phng thc fly(). Ci t giao din ny trong lp Sparrow.
41

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

Bi 3. Lp trnh GUI (Applet)


Gii thiu cc loi ng dng Th vin AWT To cc applet i tng ho Graphics K thut khung hnh ph Bi tp

Hai loi ng dng Java


Applet
Chng trnh Java chy trong mt trang web nh vo trnh duyt h tr Java.

Stand-alone Application
Giao din dng lnh (console): Tng tc vi ngi dng thng qua cc dng k t. Giao din ho (GUI): Tng tc vi ngi dng bng nhiu cch khc nhau nh hnh nh, nt nhn, biu tng Vic x l ng dng da trn cc s kin.
3

Th vin AWT
AWT (Abstract Windowing Toolkit)
L b th vin dng xy dng cc ng dng giao din ho (GUI) Cc thnh phn giao din ho nm trong gi java.awt

Cc thnh phn ca AWT


Component

Button

TextComponent

Container

MenuComponent

...

TextField

TextArea

Panel

Window

Menu

MenuBar

MenuItem

Applet

Frame

Dialog

Cc thnh phn ca AWT


Cc thnh phn container: dng cha v qun l cc thnh phn khc
Applet Frame Dialog

Cc thnh phn khc: nm trong cc thnh phn container


Nt nhn (Button) vn bn (TextField) Nhn (Label) Vng vn bn (TextArea) .
6

Thc n (Menu) Nt chn (Radio button) Danh sch (List) La chn (Choice)

Mt s phng thc ca Component


void setVisible(boolean): hin th hoc n component Dimension getSize(): tr v kch thc ca component void setSize(Dimension): thay i kch thc void setEnabled(): bt hoc tt component void repaint(): cp nht li component void update(Graphics g): c gi qua repaint() void paint(Graphics g): c gi qua update() void setBackground(Color): t mu nn ...

Xy dng cc applet
Lp Applet
Java c lp java.applet.Applet k tha t lp java.awt.Component cho php to ra cc applet trong Web. Mi lp applet do ngi dng to ra u phi k tha t lp Applet.

Xy dng cc applet
V d 1: To file TestApplet.java
import java.applet.Applet; import java.awt.Graphics; public class TestApplet extends Applet { public void paint( Graphics g) { g.drawString(Hello world!, 50, 25); } }

Dch: javac TestApplet.java


9

Xy dng cc applet
Thc thi applet
Cch 1: To file TestApplet.html c ni dung nh sau:
<APPLET CODE=TestApplet.class WIDTH=500 HEIGHT=500 </APPLET>

M file ny bng trnh duyt WEB Cch 2: Dng cng c appletviewer. G lnh:
appletviewer TestApplet.html

10

Khung ca mt applet c bn
import java.applet.Applet; import java.awt.Graphics; public class TestApplet extends Applet { public void init() {} public void start() {} public void stop() {} public void destroy {} public void paint( Graphics g) {} }

11

Hot ng ca Applet
init(): khi to applet start(): applet bt u hot ng stop(): applet chm dt hot ng destroy(): gii phng applet Ch :
paint() khng phi l phng thc ca Applet m l ca Component. paint() c gi mi khi ca s c v li.

12

Hot ng ca Applet
Vng i ca mt Applet
Np mt applet: applet c khi to v thc thi Chuyn hoc tr v trang Web: Cc phng thc stop v start s c gi Np li applet: nh qu trnh np applet Thot khi trnh duyt: phng thc stop v destroy s c gi

13

Lp Graphics
java.awt.Graphics l lp cung cp cc phng thc v ho c bn:
ng thng (Line) ng oval (Oval) Hnh ch nht (Rectangle) a gic (Polygon) Vn bn (Text) Hnh nh (Image) ...
14

Lp Graphics
H to
x (0,0) Mn hnh

15

Lp Graphics
V ng thng
public void drawLine(int x1, int y1, int x2, int y2);

V hnh ch nht
public void drawRect(int x, int y, int width, int height);

T mt hnh ch nht
public void fillRect(int x, int y, int width, int height);

Xo mt vng ch nht
public void clearRect(int x, int y, int width, int height);

V a gic
public void drawPolygon(int[] x, int[] y, int numPoint); public void drawPolygon(Polygon p);
16

Lp Graphics
import java.applet.Applet; import java.awt.Graphics; Demo public class DemoRect extends Applet { public void init() { System.out.println("Demonstration of some simple figures"); } public void paint(Graphics g) { g.drawLine(70, 300, 400, 250); g.drawRect(100, 50, 130, 170); g.fillRect(120, 70, 70, 70); int[] x = { 280, 310, 330, 430, 370 }; int[] y = { 2p0, 140, 170, 70, 90 }; g.drawPolygon(x, y, x.length);
17

Lp Graphics

18

Lp Graphics
V ng trn/elip
public void drawOval(int x, int y, int width, int height);

T ng trn/elip
public void fillOval(int x, int y, int width, int height);

V cung trn
public void drawArc(int x, int y, int width, int height,

int startAngle, int arcAngle);

V xu k t
public void drawString(String str, int x, int y);

V nh
public void drawImage(Image img, int x, int y,...);
19

Lp Graphics
import java.applet.Applet; import java.awt.Graphics; Demo public class DemoOval extends Applet { public void init() { System.out.println("Demonstration of some simple figures"); } public void paint(Graphics g) { int xstart = 70, ystart = 40, size = 100; g.drawOval(xstart, ystart, size, size); g.drawOval(xstart + (size*3)/4, ystart, size, size); g.drawOval(xstart + size/2, ystart + size/2, size, size); g.drawArc(xstart, ystart, 300, 200, 0, -90); g.drawString("good morning !", xstart + 265, ystart + 90); } } 20

Lp Graphics

21

Lp Graphics
import java.applet.Applet; Demo import java.awt.Graphics; import java.awt.Image; public class DemoImage extends Applet { public void init() { System.out.println("Demonstration of imaging"); } public void paint(Graphics g) { Image image = getToolkit().getImage("summer.jpg"); g.drawImage(image, 0, 0, this); } }
22

Lp Graphics

23

Cc lp tin ch khc
Lp Point: biu din im trn mn hnh Lp Dimension: biu din kch thc v chiu rng v chiu cao ca mt i tng Lp Rectangle: biu din hnh ch nht Lp Polygon: biu din a gic Lp Color: biu din mu sc

24

Cc lp tin ch khc
import java.applet.Applet; Demo import java.awt.*; public class DemoColor extends Applet { public void paint(Graphics g) { Dimension size = getSize(); g.setColor(Color.orange); g.fillRect(0, 0, size.width, size.height); Color color = new Color(10, 150, 20); g.setColor(color); g.drawString("I am a colorful string", size.width/2 - 50, size.height/2);

25

Cc lp tin ch khc

26

X l font v
import java.applet.Applet; Datjava.awt.*; font import public class DemoFont extends Applet { public void paint(Graphics g) { Font font = new Font("Arial", Font.BOLD, 30); g.setFont(font); g.drawString("I am font Arial, bold, size 30", 50, 50); } }

27

Bi tp ti lp
Bi 1: Sinh 100 ng thng c to ngu nhin v mu ngu nhin

28

Bi tp ti lp
Bi 2: V s thay i ca mu xanh l cy

29

Bi tp ti lp
Bi 3: Tnh ton to v v ra mn hnh cc hnh sau.

30

K thut khung hnh ph


V d v s di chuyn b nhy
import java.applet.Applet; import java.awt.*; public class DemoMove1 extends Applet { private int x = 50; private int y = 50; public void paint(Graphics g) { if (x > 300) x = 50; g.fillOval(x, y, 100, 100); delay(100); move(); }
31

K thut khung hnh ph


V d v s di chuyn b nhy
public void delay(int milisecond) { try { Thread.sleep(milisecond); } catch (Exception e) {} } public void move() { x += 5; repaint(); // ve lai cua so }

32

K thut khung hnh ph


Gii thch l do nhy:
Mi ln gi repaint() th update() c gi update() xo ni dung ca s v gi paint()

Khc phc:
V hnh vo mt khung hnh ph trong b nh thay v v trc tip ra mn hnh. Khi v xong, khung hnh ph c hin th ra mn hnh trong phng thc paint(). Np chng update() trnh vic xo ni dung ca s.
33

K thut khung hnh ph


Gii php
//... public class DemoMove2 extends Applet { //... private Image offImage; private Graphics offGraphics; public void init() { // tao khung hinh phu offImage = createImage(500, 500); // lay doi tuong do hoa de ve vao khung hinh phu offGraphics = offImage.getGraphics(); }
34

K thut khung hnh ph


Gii php
public void paint(Graphics g) { //... offGraphics.clearRect(0, 0, 500, 500); offGraphics.fillOval(x, y, 100, 100); g.drawImage(offImage, 0, 0, this); //... } public void update(Graphics g) { paint(g); } //...
35

Applet
Kh nng ca Applet
Applet c t ti mt Server trn mng Applet c chuyn ti my Client theo mt trang HTML no Khi mt trnh duyt (tng thch vi Java) nhn c trang web ny, n s ti m ca Applet v thc thi trn my client

36

Applet
Gii hn ca Applet
Khng c np cc th vin hay cc phng thc s dng m gc (native code). Khng c c v ghi ln cc tp tin ca my ang chy chng. Khng c khi ng bt k chng trnh no trn my ang chy. Khng c c bt k tnh cht no ca h thng.

37

Bi tp
1. Xy dng mt applet v ra mt khun mt nh hnh v sau:

38

Bi tp
2. V th hm s y = 3*x*x - 6*x+ 1 3. V th hm s y = sin(x)

39

Bi tp
4. Dng k thut khung hnh ph v mt qu bng chuyn ng t do trong mt applet. 5. M rng bi ton vi 2 qu bng. 6. M rng bi ton vi nn applet l mt hnh nh. 7. M rng bi ton vi qu bng l mt hnh nh v c nhiu qu bng chuyn ng ng thi.

40

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

Bi 3. Cc thnh phn GUI


Mt v d n gin M hnh x l s kin Cc thnh phn GUI c bn S kin chut S kin bn phm B qun l trnh by (layout) Bi tp

V d: Applet tnh tng 2 s


// file TinhTong.java import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class TinhTong extends Applet implements ActionListener { private TextField txtNum1, txtNum2; private Button button; // phuong thuc nay duoc goi khi applet khoi tao public void init() { txtNum1 = new TextField(8); // tao o nhap so 1 txtNum2 = new TextField(8); // tao o nhap so 2 button = new Button("Tinh Tong"); // tao nut an
3

V d: Applet tnh tng 2 s


// dua cac thanh phan vao applet Demo add(txtNum1); add(txtNum2); add(button);

// khoi tao gia tri cho o nhap txtNum1.setText("0"); txtNum2.setText("0"); // dat nghe su kien bam nut button.addActionListener(this);

};

// phuong thuc nay duoc goi khi co mot hanh dong xay ra public void actionPerformed(ActionEvent event) { repaint(); }
4

V d: Applet tnh tng 2 s


Demo // phuong thuc nay duoc goi khi ve lai cua so
public void paint(Graphics g) { int num1, num2, sum; String s1 = txtNum1.getText(); num1 = Integer.parseInt(s1); String s2 = txtNum2.getText(); num2 = Integer.parseInt(s2); sum = num1 + num2; g.drawString("Tong cua hai so la: "+sum, 35, 80); }

V d: Applet tnh tng 2 s


Gii thch applet
TextField v Button l cc lp thuc gi java.awt ActionListener v ActionEvent l cc lp thuc gi java.awt.event TinhTong cn ci t giao din ActionListener v n s trc tip x l s kin n nt button.addActionListener(this); C th dng mt lp khc nghe s kin thay cho lp TinhTong
6

M hnh x l s kin
S kin (event) c pht sinh khi ngi dng tng tc vi GUI, v d: di chuyn chut, n nt, nhp d liu vn bn, chn menu... Thng tin v s kin c lu trong mt i tng thuc lp con ca lp AWTEvent (gi java.awt.event). Chng trnh c th x l cc s kin bng cch t lng nghe s kin trn cc thnh phn GUI.
7

M hnh x l s kin
Ba thnh phn chnh ca m hnh
Event source: ngun gy ra s kin, thng l cc thnh phn GUI trong chng trnh Event object: i tng lu thng tin v s kin xy ra Event listener: i tng s nhn c thng tin khi c s kin xy ra
Event source lu mt danh sch cc Event listener v s thng bo cho chng bit mi khi c s kin xy ra
8

M hnh x l s kin
V d:
Ngi dng n mt nt To thng tin v s kin Component Thng bo c s kin xy ra EventListener EventListener EventObject

Vic thng bo s kin xy ra thc cht l vic gi mt phng thc ca EventListener vi i s truyn vo l EventObject. Cc lp con ca EventListener c th ci t cc phng thc x l s kin.
9

Mt s lp s kin
EventObject (java.util)

AWTEvent

(java.awt)

TextEvent

ComponentEvent

ActionEvent

...

InputEvent

WindowEvent

ContainerEvent

KeyEvent

MouseEvent

(java.awt.event)
10

Mt s lp s kin
S kin cp thp: dng cho hu ht cc thnh phn
FocusEvent: t/chuyn focus InputEvent: s kin phm (KeyEvent) hoc chut (MouseEvent) ContainerEvent: thm hoc xo cc component WindowEvent: ng, m, di chuyn ca s ...

11

Mt s lp s kin
S kin cp cao: dng cho mt s thnh phn c th
ActionEvent: s kin sinh ra t cc thnh phn giao tip vi ngi dng nh nhn mt nt, chn menu ItemEvent: la chn mt item trong danh sch TextEvent: thay i gi tr ca hp text ...

12

Mt s interface nghe s kin


EventListener ContainerListener FocusListener KeyListener MouseListener WindowListener ActionListener ItemListener TextListener

13

Ci t qun l s kin
Xc nh i tng s gy ra s kin (event source). V d: nt bm. Xc nh s kin cn x l trn i tng gy s kin. V d: n nt. Xc nh i tng nghe s kin (event listener) v ci t cc phng thc tng ng. V d: chnh applet s nghe s kin. ng k i tng nghe trn i tng gy ra s kin. V d:
button.addActionListener(...);

14

Cc event source v event object


Event source Button Checkbox Choice Component Event ActionEvent ItemEvent ItemEvent FocusEvent MouseEvent KeyEvent Container List ContainerEvent ActionEvent ItemEvent Ch thch Nhn nt Chn, b chn mt item Chn, b chn mt item c chn Tng tc chut Tng tc bn phm Thm, bt component Nhp kp chut mt item Chn, b chn mt item
15

ComponentEvent n, hin, di chuyn

Cc event source v event object


Event source MenuItem Scrollbar TextField Window S kin ActionEvent Ch thch Chn mt menu item Thay i vn bn Kt thc thay i vn bn Thay i ca s

AdjustmentEvent Di chuyn thanh cun ActionEvent WindowEvent

TextComponent TextEvent

16

Bng tham kho i tng nghe v phng thc cn ci t


Event Class ActionEvent Listener Interface ActionListener Listener Methods actionPerformed()

AdjustmentEvent AdjustmentListener adjustmentValueChanged() ComponentEvent ComponentListener componentHidden() componentMoved() componentResized() componentShown() ContainerEvent FocusEvent ItemEvent ContainerListener FocusListener ItemListener componentAdded() componentRemoved() focusGained() focusLost() itemStateChanged()
17

Bng tham kho i tng nghe v phng thc cn ci t


Event Class KeyEvent Listener Interface KeyListener Listener Methods keyPressed() keyReleased() keyTyped() MouseEvent MouseListener mouseClicked() mousePressed() mouseReleased() MouseMotionListener TextEvent WindowEvent TextListener WindowListener mouseDragged() mouseMoved() textValueChanged() windowClosed() windowActivated()
18

ng k i tng nghe
ng k i tng nghe ta s dng tn phng thc c cu trc nh sau:
add + loi s kin + Listener(lp nghe s kin)

V d vi nt Button
addActionListener(ActionListener)

V d vi danh sch List


addActionListener(ActionListener) addItemListener(ItemListener)

19

Mt s thnh phn GUI


Event TextComponent Checkbox Container Object Component Label Button List Choice CheckboxGroup Panel Applet TextField

20

Nhn (Label)
Nhn c dng trnh by mt chui vn bn ra mn hnh Mt s phng thc ca Label:
public Label(); // to nhn public Label(String s); // to nhn vi ni dung s public Label(String s, int align); // to v canh l void setText(String s); // t ni dung nhn void setAlignment(int align); // canh l nhn ...

21

Nhn (Label)
import java.applet.Applet; import java.awt.*; public class DemoLabel extends Applet { private Label label; public void init() { Font font = new Font("Courier", Font.BOLD, 20); label = new Label("Thu nghiem voi Label"); label.setFont(font); add(label); } public void paint(Graphics g) { showStatus("Noi dung cua Label la: + label.getText()); }
22

Nhn (Label)

23

Nt nhn (Button)
Mt s phng thc ca Button
Button(); // to nt nhn Button(String s); // to nt nhn c tn s void setLabel(String s); // i tn nt String getLabel(); // ly tn nt nhn

i tng nghe s kin nhn nt cn ci t giao tip ActionListener

24

Nt nhn (Button)
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class DemoButton extends Applet implements ActionListener { private Button blueButton; private Button whiteButton; private Button helloButton; public void init() { blueButton = new Button("Blue"); whiteButton = new Button("White"); helloButton = new Button("Hello"); blueButton.addActionListener(this); whiteButton.addActionListener(this); helloButton.addActionListener(this);
25

Nt nhn (Button)
add(blueButton); add(whiteButton); add(helloButton);

public void actionPerformed(ActionEvent event) { if (event.getSource() == helloButton) javax.swing.JOptionPane.showMessageDialog(this, "Hello !"); else { if (event.getSource() == blueButton) this.setBackground(Color.BLUE); else if (event.getSource() == whiteButton) this.setBackground(Color.WHITE); repaint(); } }
26

Nt nhn (Button)

27

vn bn (TextField)
vn bn cho php nhn d liu t bn phm trn mt dng Mt s phng thc
TextField(...); // cc cu t void setEditable(boolean b); // t/tt ch nhp void setEchoChar(char c); // t k t hin th

i tng nghe cn ci t 2 giao tip


ActionListener TextListener
Ci t phng thc textValueChanged();
28

vn bn (TextField)
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class DemoTextField extends Applet implements ActionListener { private TextField txtEdit; private TextField txtReadOnly; private TextField txtPass; private final String PASSWORD = "Java"; public void init() { txtEdit = new TextField("Your name here"); txtPass = new TextField(12); txtPass.setEchoChar('*'); txtPass.addActionListener(this); txtReadOnly = new TextField("This text is read only"); txtReadOnly.setEditable(false);
29

vn bn (TextField)
add(txtEdit); add(txtPass); add(txtReadOnly);

public void actionPerformed(ActionEvent event) { if (txtPass.getText().equals(PASSWORD)) txtReadOnly.setText("Password is valid"); else txtReadOnly.setText("Invalid password !"); }

30

La chn (Choice)
Choice cung cp kh nng la chn mt trong s cc hng mc sn c Mt s phng thc
Choice(); // cu t void addItem(String s); // thm item l s String getItem(int index);// ly item c ch s index String getSeclectedItem(); // tr v item c chn int getSelectedIndex(); // tr v index ca item c chn

Lp nghe ci t giao tip ItemListener


Ci t phng thc itemStateChanged(...)
31

La chn (Choice)
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class DemoChoice extends Applet implements ItemListener { private Choice choice; private TextField txtText; private Font font; public void init() { choice = new Choice(); choice.addItem("TimesRoman"); choice.addItem("Courier"); choice.addItem("Helvetica"); choice.addItemListener(this);

32

La chn (Choice)
txtText = new TextField("Sample Text", 16); txtText.setEditable(false); font = new Font(choice.getItem(0), Font.PLAIN, 12); txtText.setFont(font); add(choice); add(txtText);

public void itemStateChanged(ItemEvent event) { font = new Font(choice.getSelectedItem(), Font.PLAIN, 12); txtText.setFont(font); }

33

Checkbox (Hp nh du)


Checkbox cung cp cc hp tu chn cho ngi dng Mt s phng thc
Checkbox(...); // cc cu t void setLabel(String s); // t nhn mi boolean getState(); // ly trng thi hin ti

Lp nghe ci t giao tip ItemListener


Ci t phng thc itemStateChanged(...)

34

Checkbox (Hp nh du)


import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class DemoCheckbox extends Applet implements ItemListener { private Checkbox checkBold; private Checkbox checkItalic; private TextField txtText; public void init() { checkBold = new Checkbox("Bold"); checkItalic = new Checkbox("Italic"); checkBold.addItemListener(this); checkItalic.addItemListener(this); txtText = new TextField("Sample Text", 16); Font font = new Font("Courier", Font.PLAIN, 14); txtText.setFont(font);
35

Checkbox (Hp nh du)


add(txtText); add(checkBold); add(checkItalic);

public void itemStateChanged(ItemEvent event) { int valBold = Font.PLAIN; int valItalic = Font.PLAIN; if (checkBold.getState()) valBold = Font.BOLD; if (checkItalic.getState()) valItalic = Font.ITALIC; Font font = new Font("Courier", valBold + valItalic, 14); txtText.setFont(font); }

36

Checkbox v CheckboxGroup
Cc Checkbox c th c t trong mt CheckboxGroup to ra cc radio button. V d: To 3 radio button
// To 3 radio button thuc cng mt nhm. Ban u // radio1 c chn. Ti mi thi im ch c th chn mt // trong 3 radio. CheckboxGroup g = new CheckboxGroup(); Checkbox radio1 = new Checkbox(Radio1, g, true); Checkbox radio2 = new Checkbox(Radio2, g, false); Checkbox radio3 = new Checkbox(Radio3, g, false);

37

Checkbox v CheckboxGroup
// Cac import can thiet... public class DemoRadio extends Applet implements ItemListener { private Checkbox plain, bold, italic; private CheckboxGroup group; private TextField txtText; public void init() { group = new CheckboxGroup(); plain = new Checkbox("Plain", group, true); bold = new Checkbox("Bold", group, false); italic = new Checkbox("Italic", group, false); txtText = new TextField("Sample Text"); txtText.setFont(new Font("Courier", Font.PLAIN, 14)); plain.addItemListener(this); bold.addItemListener(this); italic.addItemListener(this);
38

Checkbox v CheckboxGroup
add(txtText); add(plain); add(italic); add(bold);

public void itemStateChanged(ItemEvent event) { int mode = 0; if (event.getSource() == plain) mode = Font.PLAIN; if (event.getSource() == italic) mode = Font.ITALIC; if (event.getSource() == bold) mode = Font.BOLD; txtText.setFont(new Font("Courier", mode, 14)); }

39

Danh sch (List)


List cho php ngi dng chn mt hay nhiu item t mt danh sch cc item Mt s phng thc
List(); // cu t mc nh List(int items, boolean ms); // cu t m rng String getSeclectedItem(); // ly li thnh phn c chn

Lp nghe ci t giao tip ItemListener v/hoc ActionListener


40

Danh sch (List)


// Cac import can thiet... public class DemoList extends Applet implements ItemListener, ActionListener { private List colorList; public void init() { colorList = new List(3, false); colorList.add("White"); colorList.add("Black"); colorList.add("Yellow"); colorList.add("Green"); colorList.addItemListener(this); colorList.addActionListener(this); add(colorList); }
41

Danh sch (List)


public void itemStateChanged(ItemEvent event) { List list = (List) event.getSource(); showStatus("Item " + list.getSelectedIndex() + " selected"); } public void actionPerformed(ActionEvent event) { List list = (List) event.getSource(); String s = list.getSelectedItem(); if (s.equals("White")) setBackground(Color.WHITE); if (s.equals("Black")) setBackground(Color.BLACK); if (s.equals("Yellow")) setBackground(Color.YELLOW); if (s.equals("Green")) setBackground(Color.GREEN); repaint(); }

42

Cc s kin chut
qun l cc s kin chut cn ci t giao tip
MouseListener MouseMotionListener

Cc phng thc ca MouseListener


void void void void void mousePressed(MouseEvent e); mouseClicked(MouseEvent e); mouseReleased(MouseEvent e); mouseEntered(MouseEvent e); mouseExited(MouseEvent e);
43

Cc s kin chut
Cc phng thc ca MouseMotionListener
void mouseDragged(MouseEvent e); void mouseMoved(MouseEvent e);

i tng MouseEvent
Cha cc thng tin v s kin chut

V d: Chng trnh v n gin

44

Cc s kin chut
// Cac import can thiet... public class DemoMouse extends Applet implements MouseListener { private Rectangle[] rects; private final int MAX_RECT = 100; private int numRects; public void init() { rects = new Rectangle[MAX_RECT]; numRects = 0; addMouseListener(this); setForeground(Color.RED); } public void paint(Graphics g) { for(int i=0; i< numRects; i++) g.fillRect(rects[i].x, rects[i].y, rects[i].width, rects[i].height); 45 }

Cc s kin chut
public void mouseClicked(MouseEvent e) { if (numRects < MAX_RECT) { rects[numRects++]=new Rectangle(e.getX(), e.getY(), 10, 10); repaint(); } } // Can cai dat tat ca cac phuong thuc cua giao tiep public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {}

46

Cc s kin chut

47

Cc lp adapter
Khi dng giao tip MouseListener ta phi ci t tt c cc phng thc ca n, ngay c khi ta ch dng mt trong s . Java cung cp mt s lp ci t sn nhng phng thc ny gi l cc lp Adapter). Ta ch cn tha k, ci t phng thc cn thit. Cc lp adapter cng nm trong gi java.awt.event

48

Cc lp adapter
Mt s lp adapter
Interface ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener Adapter class ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter
49

Cc s kin bn phm
Mt lp mun nghe s kin bn phm phi ci t giao tip KeyListener
void keyTyped(KeyEvent e); void keyPressed(KeyEvent e); void keyReleased(KeyEvent e);

Ch : C th s dng KeyAdapter thay cho dng giao tip KeyListener

50

Cc s kin bn phm
// Cac import can thiet... public class DemoKey extends Applet implements KeyListener { private String key; public void init() { addKeyListener(this); key = ""; } public void paint(Graphics g) { g.setFont(new Font("Arial", Font.BOLD, 72)); g.drawString(key, 100, 100); }

51

Cc s kin bn phm
public void keyTyped(KeyEvent e) { key = "" + e.getKeyChar(); repaint(); } public void keyPressed(KeyEvent e) {} public void keyReleased(KeyEvent e){}

52

Bi tp ti lp
Bi 1: Vit mt applet thc hin cng vic sau: khi chut c di chuyn vo applet th thng bo Hello Mouse, khi ra khi applet th thng bo Goodbye Mouse Bi 2: Vit mt applet cho php v ng thng bng chut (ging MS Paint)

53

B qun l b cc (Layout manager)


Java cung cp sn cc lp h tr trnh by cc thnh phn GUI. Mt s lp b cc n gin
FlowLayout: sp xp tun t BorderLayout: sp xp theo nm khu vc GridLayout: sp xp theo hng v ct

Ch :
Vi Applet v Panel, b cc mc nh l FlowLayout. C th thay i b cc bng hm setLayout
54

Lp FlowLayout
Cc thnh phn c a vo t tri sang phi, theo tng dng, nu ht dng s sang dng mi.

55

Lp FlowLayout
Mt s phng thc ca FlowLayout
FlowLayout(...); // cc cu t void setAlignment(int align); // cn l
public void init() { // tao flow layout can le phai FlowLayout layout = new FlowLayout(FlowLayout.RIGHT); setLayout(layout); add(new TextField(15)); add(new Button(Press me)); }

56

Lp BorderLayout
BorderLayout sp xp cc thnh phn theo 5 vng: EAST, WEST, SOUTH, NORTH, CENTER

57

Lp BorderLayout
// ... public void init() { // tao border layout setLayout(new BorderLayout()); add(new Button(Up), BorderLayout.NORTH); add(new Button(Left), BorderLayout.WEST); add(new Button(Right), BorderLayout.EAST); add(new Button(Down), BorderLayout.SOUTH); add(new Label(WELCOME, Label.CENTER), BorderLayout.CENTER); }

Ch : Khi add mt component theo BorderLayout cn ch r vng, nu khng component s khng c hin th.
58

Lp GridLayout
GridLayout sp xp cc thnh phn trong mt li c hng v ct. Kch thc cc component trong GridLayout l nh nhau.
private Button[] b; public void init() { // tao grid layout b = new Button[6]; b[0] = new Button("one"); b[1] = new Button("two"); b[2] = new Button("three"); b[3] = new Button("four"); b[4] = new Button("five"); b[5] = new Button("six"); setLayout( new GridLayout(3,2) ); for(int i=0; i<b.length; i++) add(b[i]); }

59

Khung cha (Container)


Khung cha l cc i tng trn c th cha cc thnh phn khc. Applet, Frame, Dialog, Panel l cc v d v khung cha.
Label 1

Container

Button TextField

Component

Label 2

60

Lp Panel (Vng cha)


Lp Panel k tha t Container. N c th c dng to ra cc giao din theo mun. V d: Mt giao din c th c nhiu panel sp xp theo mt layout nht nh, mi panel li c cc component sp xp theo mt layout ring. Ch : Panel c b cc mc nh l FlowLayout.
61

Lp Panel (Vng cha)


public void init() { Choice choice = new Choice(); choice.add("Red"); choice.add("Green"); choice.add("Blue"); Button ok = new Button("Ok"); Button cancel = new Button("Cancel"); Panel panel = new Panel(); panel.add(ok); panel.add(cancel); this.setLayout(new BorderLayout()); this.add(choice, BorderLayout.NORTH); this.add(panel, BorderLayout.CENTER);
62

Bi tp
1. Vit applet cho php nhp 3 h s a, b, c (bng TextField) sau gii phng trnh ax2 + bx + c = 0 v in kt qu. 2. Vit applet cho php nhp 3 h s a, b, c v 2 cn x1, x2 sau v th hm s ax2 + bx + c = 0 trong on [x1, x2]. 3. Vit applet to 3 nt bm. Bm nt 1 th v ngu nhin 100 ng thng ra mn hnh. Bm nt 2 th v ngu nhin 50 hnh trn. Bm nt 3 th v ngu nhin 50 hnh vung.
63

Bi tp
4. Vit mt applet cho php tnh ton n gin nh hnh bn. Ch ngi dng c th nhp d liu bng phm hoc chut.

64

Bi tp
5. Vit applet cho php ngi dng v cc hnh ch nht bng chut. Khi ngi dng n chut, ko v sau th chut th mt hnh ch nht tng ng s c v ra. M rng chng trnh: to 4 radio cho php chn v Oval, Rectangle, Fill Oval, Fill Rectangle. 6. Vit chng trnh cho php ngi dng iu khin mt qu bng. Trn mn hnh c cc nt l: To, Nh, Tri, Phi, Ln, Xung. Khi ngi dng n 1 nt th kch c/v tr ca qu bng s thay i theo. Yu cu to mt lp Ball ring bit.
65

Bi tp
7. Vit chng trnh m t tr chi d mn. Trn mn hnh c 3x3 nt bm v mi nt c th l c mn hoc khng (ngu nhin). Khi ngi dng nhn mt nt, nu nt khng c mn th cho php ngi dng n tip, cn khng th thng bo mn n v dng li. Lu l mi nt c mt s v ngi dng c th nhn phm s tng ng thay v nhn chut vo nt.

66

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

Bi 5. GUI nng cao


TextArea, Canvas CardLayout, GridBagLayout Frame, Menu, Dialog Scrollbar v ScrollPane Gii thiu cc thnh phn Swing Phng php thit k MVC Bi tp

Cc thnh phn c gii thiu


Object Component Scrollbar Canvas Container Window Dialog Frame TextComponent TextArea

FileDialog
3

Vng vn bn (TextArea)
Cho php ngi dng nhp vo nhiu dng vn bn. To i tng TextArea
TextArea(); TextArea(int rows, int columns); TextArea(String s); TextArea(String s, int rows, int columns);

Cc phng thc khc ging nh TextField


4

Vng vn bn (TextArea)
// Cac import can thiet... public class DemoTextArea extends Applet implements ActionListener { private TextArea textArea1, textArea2; private Button copy; public void init() { textArea1 = new TextArea("Sample Text", 5, 20); textArea2 = new TextArea(5, 20); copy = new Button("Copy >>>"); setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10)); copy.addActionListener(this); add(textArea1); add(copy); add(textArea2); }
5

Vng vn bn (TextArea)
public void actionPerformed(ActionEvent event) { textArea2.setText(textArea1.getText()); }

Khung v (Canvas)
Khung v l mt vng chuyn v ho, n khng b che bi cc thnh phn giao din khc. Khung v c th x l cc s kin ging nh Applet. s dng khung v, cn to mt lp khc dn xut t Canvas v ci t np chng phng thc paint(). Nn gi setSize cho khung v. To v l (0,0) tnh trong khung v.
7

Khung v (Canvas)
// Cac import can thiet... public class DemoCanvas extends Applet implements ActionListener { private Button rectButton; private Button circleButton; private MyCanvas canvas; public void init() { setLayout(new BorderLayout()); rectButton = new Button("Draw Rectangle"); circleButton = new Button("Draw Circle"); rectButton.addActionListener(this); circleButton.addActionListener(this); Panel panel = new Panel(); panel.add(rectButton); panel.add(circleButton);
8

Khung v (Canvas)
canvas = new MyCanvas(); canvas.setBackground(Color.lightGray); add(panel, BorderLayout.NORTH); add(canvas, BorderLayout.CENTER);

public void actionPerformed(ActionEvent event) { if (event.getSource() == rectButton) canvas.draw(1); else if (event.getSource() == circleButton) canvas.draw(2); }

Khung v (Canvas)
class MyCanvas extends Canvas { private int shape; public void paint(Graphics g) { Dimension size = getSize(); g.setColor(Color.BLUE); if (shape == 1) g.fillRect(40, 40, size.width-80, size.height-80); else if (shape == 2) g.fillOval(40, 40, size.width-80, size.height-80); } public void draw(int shape) { this.shape = shape; repaint(); }
10

Khung v (Canvas)

11

Thanh trt (Scrollbar)


Thanh trt cho php iu chnh gi tr trong mt khong nht nh nghe s kin trn thanh trt cn ci t giao tip AdjusmentListener.
Np chng adjustmentValueChanged()

12

Thanh trt (Scrollbar)


Bi tp: Vit chng trnh cho php iu khin font ch thng qua thanh trt. Khi thanh trt thay i th c ch hin th (drawString) thay i theo.

13

Khung cun (ScrollPane)


Khung cun l mt container cho php cha thnh phn GUI c kch thc ln hn chnh n.
Bi tp: Vit chng trnh cho php v trong mt canvas c rng ln hn kch thc ca applet. t canvas vo trong mt scroll pane.
14

B cc nng cao
CardLayout
Sp xp cc thnh phn ging nh cc l bi. Ti mi thi im ch l bi u tin c hin th. Mi l bi thng l mt Panel v trn c th dng bt k mt b cc no.

15

B cc nng cao
GridBagLayout
Sp xp cc thnh phn trong mt li ging nh GridLayout. Cc thnh phn c th c kch thc khc nhau.

Null Layout
Dng lnh setLayout(null); Phi t v tr v kch thc cho cc thnh phn thng qua cc hm: setLocation, setSize, setBounds.
16

Khung cha Frame


Frame c dng xy dng cc ng dng GUI chy c lp. Frame l mt ca s c thanh tiu v cc ng bin. B cc mc nh ca Frame l BorderLayout. Frame k tha t Window, n c th nghe cc s kin xy ra trn ca s khi ci t giao tip WindowListener. Cc ng dng c lp thng to ra ca s k tha t lp Frame.
17

V d v Frame
import java.awt.*; import java.awt.event.*; public class DemoFrame { public static void main(String[] args) { Frame frame = new Frame(Example on Frame); Label label = new Label("This is a label in Frame", Label.CENTER); frame.add(label, BorderLayout.CENTER); frame.setSize(500,500); frame.setVisible(true); frame.addWindowListener(new MyWindowListener()); } }

18

V d v Frame
// Lop nghe doc lap (external listener) class MyWindowListener extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } }

19

V d v Frame
import java.awt.*; import java.awt.event.*; public class DemoFrame2 { public static void main(String[] args) { MyFrame myFrame = new MyFrame("Example on my frame"); myFrame.setSize(250, 300); myFrame.setVisible(true); myFrame.addWindowListener(new WindowAdapter() {// Lop nghe noi khong ten (anonymous inner class listener) public void windowClosing(WindowEvent e) { System.exit(0); } }); } } 20

V d v Frame
class MyFrame extends Frame { public MyFrame(String title) { super(title); } public void paint(Graphics g) { g.setColor(Color.BLUE); g.fillOval(40, 40, 80, 80); }

21

Ci t listener
Lp nghe c lp: Lp nghe s kin l mt lp khc vi lp cha giao din. Lp nghe ni khng tn: Lp nghe khng c tn, ch nh ngha phng thc x l s kin (actionPerformed) Lp nghe ni c tn: Lp nghe c khai bo nm trong mt lp khc.
Lp ni c th truy xut cc phng thc, d liu ca lp cha n (outer class) Dng lp nghe ni c tn l mt k thut ph bin.
22

Khung cha Frame


To cc thnh phn GUI v x l s kin trong Frame cng ging nh trong Applet. Ch :
Frame khng c cc phng thc init, start nh trong Applet. Cc ng dng c lp dng Frame phi c hm main v c chy trc tip bng lnh java Cn c lnh setSize, setVisible(true) c th hin th Frame. cui chng trnh nn c lnh: System.exit(0);
23

Bi tp ti lp
Bi 1: Vit li chng trnh Tnh Tng 2 s s dng Frame. Bi 2: M rng bi 1 khi ngi dng ng ca s th s xut hin mt thng bo xc nhn vic ng. Dng JOptionPane.showConfirmDialog

24

Thc n (Menu)
Object

MenuComponent MenuItem MenuBar

Menu

CheckboxMenuItem

25

Thc n (Menu)
Menu MenuBar

Separator

MenuItem

26

Thc n (Menu)
To thc n
To v gn MenuBar vo ca s
MenuBar menuBar = new MenuBar(); myFrame.setMenuBar(menuBar);

To Menu v gn vo MenuBar
Menu fileMenu = new Menu(File); menuBar.add(fileMenu);

To MenuItem v gn vo Menu
MenuItem openItem = new MenuItem(Open); fileMenu.add(openItem);

To ng phn cch
fileMenu.addSeparator();
27

Thc n (Menu)
X l s kin trn cc MenuItem
i tng nghe cc MenuItem phi ci t giao tip ActionListener

Tham kho thm v


CheckboxMenuItem PopupMenu

28

Hp hi thoi (Dialog)
Dialog cng l mt ca s, thng dng nhp hoc hin th thng tin vi ngi dng. Hai loi hp thoi
Modal: Phi ng hp thoi trc khi chuyn sang ca s khc. Modaless: C th gi nguyn hp thoi v chuyn sang ca s khc.

29

Hp hi thoi (Dialog)
Dialog k tha t lp Window, n c b cc mc nh l BorderLayout. Hp thoi c th cha cc thnh phn GUI v x l cc s kin nh mt ca s bnh thng.

30

V d v Frame, Menu v Dialog

31

V d v Frame, Menu v Dialog


import java.awt.*; import java.awt.event.*; public class DemoFrame3 { public static void main(String[] args { MyFrame myFrame = new MyFrame("Example on my frame"); myFrame.setSize(500, 400); myFrame.setVisible(true); myFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } 32

V d v Frame, Menu v Dialog


class MyFrame extends Frame implements ActionListener { private MenuBar menuBar; private Menu menu; private MenuItem circleItem, rectItem; public MyFrame(String title) { super(title); menuBar = new MenuBar(); menu = new Menu("Draw");

setMenuBar(menuBar); menuBar.add(menu);

circleItem = new MenuItem("Circle"); rectItem = new MenuItem("Rectangle"); menu.add(circleItem); menu.add(rectItem); circleItem.addActionListener(this); rectItem.addActionListener(this);
33

V d v Frame, Menu v Dialog


public void actionPerformed(ActionEvent e) { if (e.getSource() == circleItem) { MyDialog dialog = new MyDialog(this, "Modeless Dialog: Circle", false); } }

class MyDialog extends Dialog { MyDialog(Frame parent, String title, boolean isModel) { super(parent, title, isModel); add(new Label("Hi, I am a dialog"), BorderLayout.CENTER); setSize(300, 200); setVisible(true); addWindowListener(new MyDialogListener(this)); } 34 };

V d v Frame, Menu v Dialog


// Co the dat lop nay lam lop noi (inner class) cua lop MyDialog class MyDialogListener extends WindowAdapter { Dialog dialog; MyDialogListener(Dialog dia) { dialog = dia; } public void windowClosing(WindowEvent e) { dialog.setVisible(false); dialog.dispose(); }

35

Gii thiu JFC


JFC (Java Foundation Class)
L th vin lp trnh giao din ho pht trin da trn th vin AWT JFC cung cp kh nng to giao din linh ng, uyn chuyn hn so vi AWT JFC c sn trong cc phin bn t Jdk 1.2 tr i. Cc lp ca JFC nm trong gi javax.swing

36

Cc thnh phn Swing


Cc thnh phn GUI ca Swing thng bt u bi ch J:
JButton, JLabel, JTextArea, JFrame, JPanel, JCheckBox, JRadioButton, JList, JComboBox, JScrollPane Cc thnh phn m rng nh: JTabbedPane, JProgressBar, JTable, JTree

Vic x l s kin trn cc thnh phn Swing ging nh trn cc thnh phn AWT.
37

V d v Swing
import java.awt.*; import javax.swing.*; public class HelloJFC { public static void main(String[] args) { JFrame frame = new JFrame("JFC"); Icon icon = new ImageIcon("rose.gif"); JButton button = new JButton("Rose", icon); button.setMnemonic('R'); button.setToolTipText("Button Rose"); frame.getContentPane().setLayout(new FlowLayout()); frame.getContentPane().add(button); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setVisible(true);
38

V d v Swing

39

Thit k chng trnh


Cc thnh phn ca chng trnh
D liu ca bi ton cn x l (Model) Hin th d liu ca bi ton thng qua giao din (View) iu khin tng tc vi ngi dng (Controller)

V d: Chng trnh iu khin qu bng


Model: D liu v qu bng View: Giao din hin th d liu qu bng Controller: iu khin di chuyn qu bng
40

Thit k chng trnh


Model: D liu v bng gm to tm (x,y) v bn knh bng. View: Giao din hin th gm c hnh qu bng v 2 nt iu khin. Controller: Khi n nt iu khin th qu bng di chuyn.

41

Mt s phng php thit k


Big Blob
Tt c Model, View, Controller t trong mt mt lp duy nht.

Model

View

Controller

42

V d vi Big Blob
// file TestBall.java tao ra mot big blob public class TestBall { public static void main(String[] args) { MyBallFrame myFrame = new MyBallFrame(Ball Frame); myFrame.setSize(400, 300); myFrame.setVisible(true); ... } }

43

V d vi Big Blob
// MyBallFrame la mot big blob // No chua ca model, view va controller class MyBallFrame extends Frame implements ActionListener { private int x, y, radius; // du lieu ve qua bong (model) private Button moveLeft, moveRight; // thanh phan GUI (view) ... moveLeft.addActionListener(this); moveRight.addActionListener(this); ... // xu ly su kien (controller) public void actionPerformed(ActionEvent event) ...

44

Mt s phng php thit k


Presentation-Model
Tch ring Model v Presentation (gm View + Controller)

View

Controller

Model

45

V d vi Presentation-Model
// file TestBall.java tao model va presentation public class TestBall { public static void main(String[] args) { // tao model BallModel myBall = new BallModel(50, 50, 20); // tao presentation BallPresentation myFrame = new BallPresentation(myBall); ...

46

V d vi Presentation-Model
// file BallPresentation.java chua view va controller // No co mot thanh phan du lieu la model can xu ly // Cach 1: Dung top-level listener public class BallPresentation extends Frame implements ActionListener { private BallModel ball; // model can xu ly private Button moveLeft, moveRight; // thanh phan GUI (view) ... moveLeft.addActionListener(this); moveRight.addActionListener(this); ... // xu ly su kien (controller) public void actionPerformed(ActionEvent event) ...

47

V d vi Presentation-Model
// file BallPresentation.java, cach 2: dung lop nghe la inner class public class BallPresentation extends Frame { private BallModel ball; // model can xu ly private Button moveLeft, moveRight; // thanh phan GUI (view) ... moveLeft.addActionListener(new ToLeftListener()); moveRight.addActionListener(new ToRightListener()); ... // xu ly su kien (controller) class ToLeftListener implements ActionListener { public void actionPerformed(ActionEvent event) { ball.moveLeft(); repaint(); // goi phuong thuc cua lop outer } } ... 48 }

V d vi Presentation-Model
// file BallModel.java chua du lieu va phuong thuc cua qua bong // Model khong phu thuoc vao Presentation public class BallModel { private int x, y, radius; BallModel(int x, int y, int radius) ... void moveLeft() ... void moveRight() ... int getXCenter() ... int getYCenter() ... int getRadius() ...

49

Mt s phng php thit k


Model-View-Controller
Tch ring Model, View v Controller

View

Controller

Model

50

Model-View-Controller
u i m
Cc modul c lp, d qun l C th d dng to nhiu giao din khc nhau cho cng mt chng trnh D m rng chng trnh

51

V d vi MVC
// file TestBall.java tao model, view va controller public class TestBall { public static void main(String[] args) { // tao model BallModel myBall = new BallModel(50, 50, 20); // tao view BallView ballView = new BallView(myBall); // tao controller BallController ballController = new BallController(myBall, ballView); ballView.setVisible(true); ...
52

V d vi MVC
// file BallView.java public class BallView extends Frame { private BallModel ball; // model can xu ly private Button moveLeft, moveRight; BallView(BallModel ballModel) { ball = ballModel; } public void paint(Graphics g) { g.fillOval(...); } // phuong thuc nay duoc goi boi controller public void addToLeftListener(ActionListener al) { buttLeft.addActionListener(al); } ...

53

V d vi MVC
// file BallController.java public class BallController { private BallModel ball; // model can xu ly private BallView view; // view can xu ly ... BallController(BallModel ballModel, BallView ballView) { // nhan model va view can xu ly ball = ballModel; view = ballView; // dat lang nghe tren view view.addToLeftListener(new ToLeftListener()); view.addToRightListener(new ToRightListener());

54

V d vi MVC
// file BallController.java (tiep theo) // xu ly su kien thong qua inner class class ToLeftListener implements ActionListener { public void actionPerformed(ActionEvent event) { ball.moveLeft(); view.repaint(); } } ...

55

V d vi MVC
// file BallModel.java chua du lieu va phuong thuc cua qua bong // Model khong phu thuoc vao View va Controller public class BallModel { private int x, y, radius; BallModel(int x, int y, int radius) ... void moveLeft() ... void moveRight() ... int getXCenter() ... int getYCenter() ... int getRadius() ...

56

Case study: Chng trnh i tin


Vit chng trnh cho php tnh s lng tin VN tng ng vi mt s lng USD cho trc. Bit rng 1 la = 16,798 . M t giao din nh sau:

57

Case study: Chng trnh i tin


ExchangeModel ? ExchangeView ? ExchangeController ? Ci t v th nghim

58

Ti liu tham kho


http://www.dickbaldwin.com/toc.htm http://leepoint.net/notes-java/index.html http://java.sun.com/developer/onlineTrainin g/GUI/Swing2/shortcourse.htm

59

Bi tp
1. Vit chng trnh cho php ngi dng chn mt trong hai ch l Line v Point (dng Checkbox), sau ngi dng c th dng chut v trong mt Canvas nm gia mn hnh (ging MS Paint). 2. Vit li cc chng trnh lin quan ti Graphics s dng Frame. 3. Vit li cc chng trnh lin quan ti thnh phn giao din GUI s dng Frame.

60

Bi tp
4. Vit chng trnh to 3 menu trong mt Frame nh sau:
Colors Red Green Blue Shapes Circle Rect Line Help About

Menu Colors cho php chn mu, menu Shapes cho php chn hnh. Khi ngi dng chn menu v n nt draw trn Frame th chng trnh v ra hnh v mu c chn. Menu Help About hin th hp thoi gii thiu v chng trnh.
61

Bi tp
5. Vit chng trnh tnh din tch cc hnh: To mt Frame trong bn tri c 3 la chn l Circle, Rectangle v Triangular (dng Checkbox). Khi ngi dng chn mt trong cc hnh th bn phi s hin th cc nhp liu tng ng: Circle c mt nhp l Radius, Rectangle c 2 nhp l Width v Height, Triangular c 3 nhp l 3 cnh a, b, c. Sau ngi dng chn nt Compute th chng trnh tnh v hin th kt qu ln mn hnh. (Dng CardLayout)
62

Bi tp
6. Vit chng trnh to 2 menu item l Nhp hng v Bn hng. Khi ngi dng chn nhp hng th hin th Frame cho php nhp vo tn hng, s lng, n gi (lu thng tin ny vo mng). Khi ngi dng chn Bn hng th hin th Frame (hoc Dialog) cho php nhp vo tn ngi mua v cho php chn mua mt trong s cc mt hng c sn; sau hin th s tin m ngi phi tr. (Thit k theo MVC)

63

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

Bi 6. X l ngoi l
X l li v ngoi l Khi try/catch/finally Cc lp ngoi l Xy dng lp ngoi l Lan truyn ngoi l Tung li ngoi l Bi tp

X l li v ngoi l
Trong mt s ngn ng nh C, vic x l li thng c ci t ngay ti cc bc thc hin ca chng trnh. Cc hm s tr v mt cu trc li khi gp li. V d: Tm kim phn t trong mt danh sch
ErrorStruct error = new ErrorStruct(); TableEntry entry = lookup(Marianna, employee, error); if (entry == null) { return error; }
3

X l li v ngoi l
M lnh v m x l li nm xen k khin lp trnh vin kh theo di c thut ton chnh ca chng trnh. Khi mt li xy ra ti hm A, tt c cc li gi hm lng nhau n A u phi x l li m A tr v.

X l li v ngoi l
Trong Java, vic x l li c th c ci t trong mt nhnh c lp vi nhnh chnh ca chng trnh. Li c coi nh nhng trng hp ngoi l (exceptional conditions). Chng c bt/nm (catch and throw) khi c li xy ra. => Mt trng hp li s ch c x l ti ni cn x l. => M chnh ca chng trnh sng sa, ng vi thit k thut ton.
5

V d 1
import java.awt.Point; public class MyArray { public static void main(String[ ] args) { System.out.println("Goi phuong thuc methodeX()"); methodeX(); System.out.println("Chuong trinh ket thuc binh thuong"); } public static void methodeX() { Point[ ] pts = new Point[10]; for(int i = 0; i < pts.length; i++) { pts[i].x = i; pts[i].y = i+1; } } }
6

Kt qu thc thi v d 1
Goi phuong thuc methodeX() Exception in thread "main" java.lang.NullPointerException at MyArray.methodeX(MyArray.java:14) at MyArray.main(MyArray.java:7)

Gii thch: H thng tung ra mt exception thuc lp NullPointerException khi gp li. Sau chng trnh kt thc.

V d 2
public class MyDivision { public static void main(String[ ] args) { System.out.println("Goi phuong thuc A()"); A(); System.out.println("Chuong trinh ket thuc binh thuong"); } public static void A() { B(); } public static void B() { C(); } public static void C() { float a = 2/0; } }
8

Kt qu thc thi v d 2
Goi phuong thuc A() Exception in thread "main" java.lang.ArithmeticException: / by zero

at at at at

MyDivision.C(MyDivision.java:14) MyDivision.B(MyDivision.java:11) MyDivision.A(MyDivision.java:8) MyDivision.main(MyDivision.java:4)

Gii thch: Phng thc A() gi B(), B() gi C(), C() gy ra li chia cho 0 v h thng nm ra mt exception thuc lp ArithmeticException. Sau chng trnh kt thc.

Ngoi l
Khi mt phng thc gp li no , v d nh chia khng, vt kch thc mng, m file cha tn ti th cc ngoi l s c nm ra. Chng trnh dng li ngay lp tc, ton b phn m pha sau s khng c thc thi. Java h tr cch thc x l ngoi l (exception handling) tu theo nhu cu ca chng trnh.
10

X l ngoi l
Khi try/catch
t on m c kh nng xy ra ngoi l trong khi try t on m x l ngoi l trong khi catch Khi xy ra ngoi l trong khi try, cc cu lnh trong khi catch s c thc hin tu vo kiu ca ngoi l. Sau khi thc hin xong khi catch, iu khin s c tr li cho chng trnh.
11

Khi try/catch
V d 1:
try { methodeX(); System.out.println(Cau lenh ngay sau methodX());

} catch (NullPointerException e) { System.out.println(Co loi trong khoi try); } System.out.println(Cau lenh sau try/catch);

12

Khi try/catch
V d 2:
try { A(); } catch (Exception e) { System.out.println(Co loi trong A()); }

V d 3:
try { x = System.in.read(); System.out.println(x = + x); } catch (IOException e) { System.out.println(Error: + e.getMessage()); }
13

Khi try/catch
V d 4:
String s = buff.readLine(); int a = Integer.parseInt(s); x[i++] = a; } catch (IOException e) { System.out.println(Error IO: + e.getMessage()); } catch (NumberFormatException e) { System.out.println(Error Format: + e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(Error Index: + e.getMessage()); } try {

14

Khi finally
Khi mt ngoi l xy ra, chng trnh dng li, mt s cng vic dn dp c th s khng c thc hin (v d nh ng file). Khi finally m bo rng cc cu lnh trong lun c thc hin, k c khi ngoi l xy ra.
try { doSomething(); // phng thc ny c th gy ra ngoi l } finally { cleanup(); }

15

Tm tt v x l ngoi l
Cc ngoi l xy ra khi gp li. C th bt v x l cc ngoi l bng cch s dng khi try/catch. Nu khng chng trnh s kt thc ngay (vi ng dng console) hoc tip tc tn ti (vi ng dng GUI). Khi bt ngoi l, phi bit r kiu ngoi l cn bt. C th dng kiu cha Exception. chc chn vic dn dp lun c thc hin, dng khi finally. C th kt hp try/catch/finally.
16

Mt s lp ngoi l
Object Throwable Error Exception

AssertionError RuntimeException IOException ClassNotFoundException NullPointerException ArithmeticException

17

Mt s lp ngoi l
Lp Throwable
C mt bin String lu thng tin chi tit v ngoi l xy ra Mt s phng thc c bn
Throwable(String s); // To mt ngoi l c tn l s. String getMessage(); // Ly thng tin v ngoi l void printStackTrace(); // In ra tt c cc thng tin lin quan n ngoi l

18

Mt s lp ngoi l
Lp Exception
C nhiu ngoi l thuc lp con ca Exception. Ngi dng c th to ra cc ngoi l k tha t Exception.

Lp Error
Ch nhng li nghim trng v khng d on trc c nh ThreadDead, LinkageError, VirtualMachineError... Cc ngoi l kiu Error t c x l.
19

Mt s lp ngoi l
RuntimeException: Ch cc ngoi l c th xy ra khi JVM thc thi chng trnh
NullPointException: con tr null OutOfMemoryException: ht b nh ArithmeticException: li ton hc, li chia khng ClassCastException: li p kiu ArrayIndexOutOfBoundsException: vt qu ch s mng ...
20

Hai loi ngoi l


Ngoi l unchecked
L cc ngoi l khng bt buc phi c kim tra. Gm RuntimeException, Error v cc lp con ca chng.

Ngoi l checked
L cc ngoi l bt buc phi c kim tra. Gm cc ngoi l cn li.
21

Ch vi ngoi l checked
Gi s method1 gi method2 v method2 l phng thc c kh nng nm ngoi l kiu checked, lc :
hoc method2 phi nm trong khi try/catch. hoc phi khai bo method1 c kh nng nm (throws) ngoi l.

22

V d: Ngoi l IOException
Cch 1: try/catch
public static void main(String[] args) { try { String s = buff.readLine(); } catch (IOException e) { ... } }

Cch 2: Khai bo throws


public static void main(String[] args) throws IOException { String s = buff.readLine(); }
23

Bi tp ti lp
Bi 1: Ci t x l cc ngoi l cho chng trnh tnh thng 2 s bng giao din GUI. Bi 2: Ci t x l li bng cch dng ngoi l cho v d phn u bi.

24

Ngoi l do ngi dng to


nh ngha lp ngoi l
public class MyException extends Exception { public MyException(String msg) { super(msg); } }
// file MyException.java

25

Ngoi l do ngi dng to


S dng ngoi l
Khai bo kh nng tung ngoi l

// file ExampleException.java public class ExampleException { public void copy(String fileName1, String fileName2) throws MyException { if (fileName1.equals(fileName2)) throw new MyException("File trung ten"); // tung ngoi l } System.out.println("Copy completed");

Tung ngoi l
26

Ngoi l do ngi dng to


S dng ngoi l
public static void main(String[] args) { ExampleException obj = new ExampleException(); try { String a = args[0]; String b = args[1]; obj.copy(a,b); } catch (MyException e) { System.out.println(e.getMessage()); } }

27

Lan truyn ngoi l


Tnh hung
Gi s trong main() gi phng thc A(), trong A() gi B(), trong B() gi C(). Khi mt ngn xp cc phng thc c to ra. Gi s trong C() xy ra ngoi l.

28

Lan truyn ngoi l


C() B() A() main()
C() tung ngoi l

B() A() main()

Nu C() gp li v tung ra ngoi l nhng trong C() li khng x l ngoi l ny, th ch cn mt ni c th x l chnh l ni m C() c gi, l trong phng thc B(). Nu trong B() cng khng x l th phi x l ngoi l ny trong A()Qu trnh ny gi l lan truyn ngoi l. Nu n main() cng khng x l ngoi l c tung t C() th chng trnh s phi dng li.
29

Nm li ngoi l
Trong khi catch, ta c th khng x l trc tip ngoi l m li nm li ngoi l cho ni khc x l.
catch (IOException e) { throw e;

Ch : Trong trng hp trn, phng thc cha catch phi bt ngoi l hoc khai bo throws cho ngoi l (nu l loi checked).
30

Ch khi s dng ngoi l


Khng nn s dng ngoi l thay cho cc lung iu khin trong chng trnh.
V d: Kim tra delta trong chng trnh gii phng trnh bc 2.

Nn thit k v s dng ngoi l mt cch thng nht cho ton b d n. Mt s x l li bng ngoi l ph bin l: ht b nh, vt qu ch s mng, con tr null, chia cho 0, i s khng hp l...
31

Bi tp
1. Vit chng trnh cho php tnh gi tr ca biu thc:
5x - y

A=
2x + 7y

Yu cu x l cc ngoi l c th xy ra. 2. Vit chng trnh cho php to mt mng 2 chiu c mxn vi m,n nhp t bn phm. Ci t cc x l ngoi l cn thit.

32

Bi tp
3. Xy dng lp ngoi l DateException cho cc li v ngy thng. 4. Vit chng trnh cho php ngi dng nhp vo ngy, thng nm, nu thng tin ny khng hp l s tung ra mt ngoi l DateException, sau thng bo cho ngi nhp bit v cho php ngi dng nhp li.

33

Bi tp
5. Tm hiu li lp Candidate hc (d liu gm m th sinh, tn v im thi 3 mn). iu g s xy ra khi to mt i tng thuc lp Candidate vi d liu a vo khng hp l ? Ci t lp CandidateException bt cc li nh trn. Yu cu khi c li th s cho bit c tn v m th sinh b li.

34

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

Bi 7. Lung v x l file
Khi nim lung Cc lung byte i tng serializable Cc lung k t File truy cp ngu nhin Lp File Bi tp

Khi nim lung (stream)


Lung l mt dng chy ca d liu c gn vi cc thit b vo ra. Hai loi lung:
Lung nhp: Gn vi cc thit b nhp nh bn phm, my scan, file... Lung xut: Gn vi cc thit b xut nh mn hnh, my in, file...

Vic x l vo ra thng qua lung gip cho lp trnh vin khng phi quan tm n bn cht ca thit b vo ra.
3

Khi nim lung (stream)


Chng trnh c trn lung nhp ly d liu t thit b nhp, ghi vo lung xut a d liu ra thit b xut
Input Stream
Input Device

Program
Output Device

Output Stream
4

Cc lung c bn
Lung byte: L dng chy cc byte
InputStream: Lung nhp byte c bn OutputStream: Lung xut byte c bn

Lung k t: L dng chy cc k t (char)


Reader: Lung nhp k t c bn Writer: Lung xut k t c bn

Cc lp lung nm trong gi java.io

Lung byte
ByteArrayInputStream DataInputStream FileInputStream FilterInputStream InputStream ObjectInputStream PipedInputStream SequenceInputStream StringBufferInputStream
6

BufferedInputStream LineNumberInputStream PushbackInputStream

Lung byte
ByteArrayOutputStream DataOutputStream FileOutputStream FilterOutputStream OutputStream ObjectOutputStream PipedOutputStream BufferedOutputStream PrintStream

Lung nhp/xut byte c bn


InputStream v OutputStream l hai lp gc ca mi lung nhp/xut byte (abstract).
Object

InputStream

OutputStream

Lp InputStream
Mt s phng thc ca InputStream
abstract int read() throws IOException c mt byte t lung. Nu cui lung s tr v -1 int read(byte[] b) throws IOException c mt dy byte t lung void close() throws IOException ng lung nhp int available() throws IOException Tr v s byte c th c tip long skip(long n) throws IOException B qua n byte
9

Lp OutputStream
Mt s phng thc ca OutputStream
abstract void write(int b) throws IOException Ghi mt byte ra lung void write(byte[] b) throws IOException Ghi mt dy byte ra lung void close() throws IOException ng lung void flush() throws IOException Dn xut lung

10

Cc lung file
c s dng xut nhp vi file. Lung nhp t file: FileInputStream
FileInputStream(String name) FileInputStream(File f)

Lung xut ra file: FileOutputStream


FileOutputStream(String name) FileOutputStream(File f) FileOutputStream(String name, boolean append)

Phng thc nhp/xut ca cc lung file ging nh ca cc lung nhp xut c bn


11

V d: c v hin th file (v1)


import java.io.*; public class ReadFile { public static void main(String[] args) { try { FileInputStream f = new FileInputStream("readme.txt"); int ch; while ( (ch = f.read()) != -1 ) { System.out.print((char)ch); } f.close(); } catch (FileNotFoundException d) { System.out.println("File not found"); } catch (IOException d) { System.out.println("Can not read file"); } } 12 }

V d: Ghi d liu ra file


import java.io.*; public class WriteFile { public static void main(String[] args) { byte buffer[] = new byte[80]; try { System.out.println("Enter a string to write to file: "); int num = System.in.read(buffer); FileOutputStream f = new FileOutputStream("line.txt"); f.write(buffer, 0, num); f.close(); } catch (IOException e) { System.out.println("Error IO file"); } } }
13

Lung lc (filter stream)


Lung lc c kh nng kt ni vi cc lung khc v x l d liu theo cch ring ca n. FilterInputStream v FilterOutputStream l 2 lp lung lc c bn.
Filter Stream Input Stream
Input Device

14

Lung nhp/xut d liu s cp


DataInputStream v DataOutputStream l 2 lp lc cho php nhp xut d liu thuc cc kiu s cp.
DataInputStream
char long float ...

Input Stream
Input Device

15

Lung nhp/xut d liu s cp


Mt s phng thc ca DataInputStream
float readFloat() throws IOException int readInt() throws IOException long readLong() throws IOException String readUTF() thr ows IOException void void void void writeFloat(float v) throws IOException writeInt(int b) throws IOException writeLong(long v) throws IOException writeUTF(String s) throws IOException

Mt s phng thc ca DataOutputStream

16

V d: To file cc s ngu nhin


try { FileOutputStream f = new FileOutputStream("randnum.dat"); DataOutputStream outFile = new DataOutputStream(f); for(int i = 0; i < 20; i++) outFile.writeInt( (int) (Math.random()*1000) ); outFile.close(); } catch (IOException e) { ... }

FileInputStream g = new FileInputStream("randnum.dat"); DataInputStream inFile = new DataInputStream(g); int num; while (true) { num = inFile.readInt(); System.out.println("num = " + num); } } catch (EOFException e) { System.out.println("End of file"); 17 } catch (IOException e) { ... }

try {

Lung m (buffered stream)


Lung m gip gim bt s ln c ghi d liu trn thit b vo ra, tng tc nhp/xut. Cc lp lung m
BufferedInputStream (m nhp) BufferedOutputStream (m xut)

18

V d: c v hin th file (v2)


// version 2 ny c th em li hiu qu ng k hn version 1 trn // nhng file c kch thc ln try { FileInputStream f = new FileInputStream("readme.txt"); BufferedInputStream inFile = new BufferedInputStream(f); int ch; while ( (ch = inFile.read()) != -1 ) { System.out.print((char)ch); } } catch (IOException e) { System.out.println("Error IO file"); }

19

Ghp ni nhiu lung


C th dng lung lc ghp ni nhiu lung vi nhau. V d:
FileInputStream fStream = new FileInputStream("data.dat"); BufferedInputStream bStream = new BufferedInputStream(fStream); DataInputStream dStream = new DataInputStream(bStream); ... dStream.close();

20

System.in v System.out
System.in
i tng nhp chun, gn vi bn phm. Thuc lp InputStream.

System.out
i tng xut chun, gn vi mn hnh. Thuc lp PrintStream.

Lp PrintStream
Cho php hin th biu din ca d liu. PrintStream k tha t FilterOutputStream
21

Lp PrintStream
// Chng trnh ny c mt file cc s thc v ghi vo file khc // di dng vn bn try { FileInputStream f = new FileInputStream("float.dat"); DataInputStream inStream = new DataInputStream(f); FileOutputStream ff = new FileOutputStream("ketqua.txt"); PrintStream pStream = new PrintStream(ff); int count = 0; while (true) { float num = inStream.readFloat(); count++; pStream.println("Float " + count + " = " + num); } inStream.close(); pStream.close(); } catch (EOFException e) { System.out.println(End of file); } catch (IOException e) {...}

22

Bi tp ti lp
Bi 1: Vit chng trnh m xem trong mt file vn bn cho trc c bao nhiu cu. Bit rng cc cu kt thc bi du chm. Bi 2: Vit chng trnh to file ghi 100 s Fibonacci u tin. Vit chng trnh th hai c v hin th d liu t file ny.

23

Lung nhp/xut i tng


lu li mt i tng, ta c th lu ln lt tng thuc tnh ca n. Khi c li i tng ta phi to i tng mi t cc thuc tnh ghi. => Di dng, km linh hot. Java h tr c/ghi cc i tng mt cch n gin thng qua lp ObjectInputStream v ObjectOutputStream. Mt i tng mun c th c c/ghi phi ci t giao tip java.io.Serializable
24

V d: Ghi li tn v ngy sinh


try {

FileOutputStream f = new FileOutputStream("birthfile.dat"); ObjectOutputStream oStream = new ObjectOutputStream(f); String babyName = "Briney Spears"; Date today = new Date(); oStream.writeObject(babyName); oStream.writeObject(today);

oStream.close(); } catch (IOException e) { System.out.println(Error IO file); }

25

V d: c tn v ngy sinh
try { FileInputStream f = new FileInputStream("birthfile.dat"); ObjectInputStream inStream = new ObjectInputStream(f); String name = (String) inStream.readObject(); Date birthDate = (Date) inStream.readObject(); System.out.println("Name of baby: " + name); System.out.println("Birth date: " + birthDate); inStream.close(); } catch (IOException e) { System.out.println(Error IO file); } catch (ClassNotFoundException e) { System.out.println(Class of serialized object not found); }
26

c/ghi i tng t to
// file Student.java public class Student implements Serializable

private String name; private int age;

Student(String name, int age) { this.name = name; this.age = age; }


public String toString() { String ret = "My name is " + name + "\nI am " + age + " years old"; return ret; }
27

c/ghi i tng t to
// file WriteMyObject.java import java.io.*; public class WriteMyObject { public static void main(String[] args) { try { FileOutputStream f = new FileOutputStream("student.dat"); ObjectOutputStream oStream = new ObjectOutputStream(f); Student x = new Student("Bill Gates", 18); oStream.writeObject(x); oStream.close(); } catch (IOException e) { System.out.println(Error IO file); }
28

c/ghi i tng t to
FileInputStream g = new FileInputStream("student.dat"); ObjectInputStream inStream = new ObjectInputStream(g); Student y = (Student) inStream.readObject(); System.out.println(y.toString()); inStream.close(); } catch (ClassNotFoundException e) { System.out.println(Class not found); } catch (IOException e) { System.out.println(Error IO file); } try {

29

c/ghi i tng t to
i tng c th ci t 2 phng thc sau thc hin c/ghi theo cch ring ca mnh.
private void writeObject(ObjectOutputStream out) throws IOException private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException

30

Lung k t
T Jdk 1.1, Java h tr c v thao tc trn lung i vi cc k t Unicode (2 byte). Lung k t c bn
Reader (c) Writer (ghi)
Object

Reader

Writer
31

Lung k t
CharArrayReader InputStreamReader FilterReader Reader StringReader PipedReader BufferedReader LineNumberReader FileReader PushBackReader

32

Lung k t
CharArrayWriter OutputStreamWriter FilterWriter Writer StringReader PipedWriter BufferedWriter StringWriter
33

FileWriter

Kt ni lung byte v lung k t


C th chuyn t lung byte sang lung k t nh cc lp
InputStreamReader OutputStreamReader

V d:
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in)); String s = buff.readLine(); ...

34

Lung k t v Unicode
Unicode Encoding
UTF-8 UTF-16

c/ghi file vi cc k t Unicode


Kt ni t lung FileInputStream/FileOutputStream vo InputStreamReader/OutputStreamWriter (c th vo tip BufferedReader/BufferedWriter) Ch r cch encoding
35

V d: Ghi file Unicode


try { OutputStreamWriter buff = new OutputStreamWriter(new FileOutputStream("unicode.txt"), "UTF-16"); buff.write(''); buff.write(''); String s = "\r\nvy h"; buff.write(s, 0, s.length()); buff.close(); } catch (IOException e) { System.out.println(Error IO file); }

36

V d: c file Unicode
try { InputStreamReader buff = new InputStreamReader(new FileInputStream("unicode.txt"), "UTF-16"); int ch; while ( (ch = buff.read()) != -1) { System.out.print((char)ch); // ch console s khng hin th c k t c // du, nn hin th trong TextField hoc TextArea } buff.close(); } catch (IOException e) { System.out.println(Error IO file); }

37

Ch khi son tho m


Mun a trc tip ting Vit Unicode vo cng cc on m Java cn phi s dng Notepad hoc cc phn mm h tr son tho ting Vit. Cc bc cn thc hin
Lu file source code di dng Unicode G lnh bin dch
javac encoding unicode filename.java

Lnh thng dch


java filename (nh bnh thng)
38

File truy nhp ngu nhin


Hai hn ch ca vic x l file thng qua lung
Khng th c v ghi file cng mt lc Truy nhp file mang tnh tun t

Java h tr vic truy nhp v x l file mt cch t do thng qua lp RandomAccessFile.

39

File truy nhp ngu nhin


Cc phng thc c bn
RandomAccessFile(String name, String mode) // cu t, trong mode c th l r, w, rw int readInt(); // c s nguyn void writeInt(int v); // ghi s nguyn long readLong(); // c s long void writeLong(long v); // ghi s long void seek(long pos); // di chuyn v tr con tr file long getFilePointer(); // ly v tr ca con tr file long length(); // ly kch c ca file void close(); // ng file ...
40

V d vi RandomAccessFile
try { RandomAccessFile f = new RandomAccessFile("randfile.dat","rw"); f.writeBoolean(true); f.writeInt(123456); f.writeChar('j'); f.writeDouble(1234.56); f.seek(1); System.out.println(f.readInt()); System.out.println(f.readChar()); System.out.println(f.readDouble()); Kt qu f.seek(0); System.out.println(f.readBoolean()); 123456 f.close(); j } catch (IOException e) { 1234.56 System.out.println(Error IO file); true }
41

Ch khi ng file
Nu lnh f.close() trong khi try th c th lnh ny s khng c thc hin khi c li cc lnh pha trn. C th vit li nh sau:

42

Ch khi ng file
FileInputStream f = null; try { f = new FileInputStream("somefile.txt"); // c file } catch (IOException e) { // hin th li } finally { if (f != null) { try { f.close(); // ng file } catch (Exception e) { // thng bo li khi ng file } } }
43

Lp File
Lp File cho php ly thng tin v file v th mc. Mt s phng thc ca File
boolean exists(); // kim tra s tn ti ca file boolean isDirectory(); // kim tra xem file c phi l th mc String getParent(); // ly th mc cha long length(); // ly c file (byte) long lastModified(); // ly ngy sa file gn nht String[] list(); // ly ni dung ca th mc

44

V d: Hin th thng tin file


import java.io.*; import java.util.Date; public class FileInfo { public static void main(String[] args) { File file = new File("randfile.dat"); if ( file.exists() ) { System.out.println("Path is: " + file.getAbsolutePath()); System.out.println("It's size is: " + file.length()); Date dateModified = new Date(file.lastModified()); System.out.println("Last update is: " + dateModified); } else System.out.println("The file does not exist"); } }
45

V d: Hin ni dung th mc
import java.io.*; public class DirList { public static void main(String[] args) { File dir = new File(".", ""); if ( dir.isDirectory() ) { String[] subFiles = dir.list(); for(int i=0; i < subFiles.length; i++) if (new File(subFiles[i]).isDirectory()) System.out.println(subFiles[i] + " <DIR>"); else System.out.println(subFiles[i]); } else System.out.println("The file is not a directory"); } }

46

Tm tt v x l file
Nn dng DataInputStream v DataOutputStream nhp/xut cc d liu kiu s cp (int, float...) Nn dng ObjectInputStream v ObjectOutputStream nhp/xut cc i tng. Nn kt hp lung file v lung c/ghi k t nhp xut cc file k t Unicode. Nn dng RandomAccessFile nu mun c/ghi t do trn file. Dng lp File ly thng tin v file
47

Mt s lp khc
java.io.StreamTokenizer

java.io.FilenameFilter java.awt.FileDialog javax.swing.JFileChooser ...

48

Bi tp
1. Vit chng trnh mycopy s dng nh sau: java mycopy filename1 filename2
Nu filename1 v filename2 l 2 file th chng trnh copy ni dung ca filename1 sang filename2 Nu filename2 l th mc th copy filename1 sang th mc filename2 Nu filename1 c tn l con th cho php to filename2 vi ni dung g t bn phm (ging lnh copy con)

2. Vit chng trnh mydir s dng nh sau: java mydir filename. Chng trnh c chc nng ging lnh dir ca DOS.
49

Bi tp
3. Vit chng trnh cho php ngi dng chn mt file vn bn, sau hin th ni dung ca file ny trong mt i tng TextArea. (Dng lp JFileChooser m hp thoi chn file). 4. Vit chng trnh c cu trc ca mt nh bitmap v hin th ra mn hnh. Tham kho cu trc nh bitmap trn Internet.

50

Bi tp
5. Vit chng trnh qun l mt danh sch th sinh (Candidate). Chng trnh cho php thm th sinh, tm kim, cp nht... Khi bt u, chng trnh s ly d liu t file thisinh.dat. Khi kt thc, chng trnh ghi li danh sch sinh vin vo file. C th dng RandomAccessFile hoc dng ObjectOutputStream v ci t Serializable.

51

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

Bi 8. Collections
Cu trc d liu trong Java
Linked List Stack v Queue Tree

Collections Framework
Danh sch (List) Tp hp (Set) Bng nh x (Map)

Bi tp
2

Cu trc d liu
Cu trc d liu l cch t chc d liu gii quyt vn . Mt s cu trc d liu ph bin:
Mng (Array) Danh sch lin kt (Linked List) Ngn xp (Stack) Hng i (Queue) Cy (Tree)

Linked List
Linked list l cu trc gm cc node lin kt vi nhau thng qua cc mi lin kt. Node cui linked list c t l null nh du kt thc danh sch. Linked list gip tit kim b nh so vi mng trong cc bi ton x l danh sch. Khi chn/xo mt node trn linked list, khng phi dn/dn cc phn t nh trn mng. Vic truy nhp trn linked list lun phi tun t .
4

Linked List
Th hin Node thng qua lp t tham chiu (self-referential class)
class Node { private int data; private Node nextNode; // constructors and methods ... }

15

10

Linked List
Mt linked list c qun l bi tham chiu ti node u v node cui.
firstNode lastNode

...

Ci t Linked List
// Dinh nghia mot node trong linked list class ListNode { int data; ListNode nextNode; ListNode(int value) { this(value, null); } ListNode(int value, ListNode node) { data = value; nextNode = node; } int getData() { return data; } ListNode getNext() { return nextNode; }
7

Ci t Linked List
// Dinh nghia lop LinkedList public class LinkedList { private ListNode firstNode; private ListNode lastNode; public LinkedList() { firstNode = lastNode = null; } public void insertAtFront(int insertItem) { if ( isEmpty() ) firstNode = lastNode = new ListNode( insertItem ); else firstNode = new ListNode( insertItem, firstNode ); }
8

Ci t Linked List
public void insertAtBack( int insertItem ) { if ( isEmpty() ) firstNode = lastNode = new ListNode( insertItem ); else lastNode = lastNode.nextNode = new ListNode( insertItem ); } public int removeFromFront() { int removeItem = -1; if ( ! isEmpty() ) { removeItem = firstNode.data; if ( firstNode == lastNode ) firstNode = lastNode = null; else firstNode = firstNode.nextNode; } return removeItem; }

Ci t Linked List
public int removeFromBack() { int removeItem = -1; if ( ! isEmpty() ) { removeItem = lastNode.data; if ( firstNode == lastNode ) firstNode = lastNode = null; else { ListNode current = firstNode; while ( current.nextNode != lastNode ) current = current.nextNode; lastNode = current; current.nextNode = null; } } return removeItem; }

10

Ci t Linked List
public boolean isEmpty() { return (firstNode == null); } public void print() { ListNode node = firstNode; while (node != null) { System.out.print(node.data + " "); node = node.nextNode; } System.out.println("\n"); }

11

M t insertAtFront
(a)

firstNode 7 new ListNode 12 11

(b)

firstNode 7 new ListNode 12 11

12

M t insertAtBack
(a)

firstNode

lastNode

new ListNode

12

11

(b)

firstNode

lastNode

new ListNode

12

11

13

M t removeFromFront
(a)

firstNode

lastNode

12
(b)

11

5 lastNode

firstNode

12

11

removeItem

14

M t removeFromBack
(a)

firstNode

lastNode

12
(b)

7 current

11

5 lastNode

firstNode

12

11

removeItem

15

S dng Linked List


public class ListTest { public static void main( String args[] ) { LinkedList list = new LinkedList(); list.insertAtFront( 5 ); list.insertAtFront( 7 ); list.insertAtBack( 9 ); list.insertAtBack( 8 ); list.insertAtBack( 4 ); list.print(); list.removeFromFront(); list.removeFromBack(); list.print();

16

Stack
Stack l mt cu trc theo kiu LIFO (Last In First Out), phn t vo sau cng s c ly ra trc. Hai thao tc c bn trn Stack
Chn phn t: Lun chn vo nh Stack (push) Ly ra phn t: Lun ly ra t nh Stack (pop)

17

Ci t Stack
public class Stack { private LinkedList stackList; public Stack() { stackList = new LinkedList(); } public void push( int value ) { stackList.insertAtFront( value ); } public int pop() { return stackList.removeFromFront(); } public boolean isEmpty() { return stackList.isEmpty(); } public void print() { stackList.print(); }

18

S dng Stack
public class StackTest { public static void main(String[] args) { Stack stack = new Stack(); stack.push(5); stack.push(7); stack.push(4); stack.push(8); stack.print(); stack.pop(); stack.pop(); } stack.print();

19

Queue
Queue (Hng i) l cu trc theo kiu FIFO (First In First Out), phn t vo trc s c ly ra trc. Hai thao tc c bn trn hng i
Chn phn t: Lun chn vo cui hng i (enqueue) Ly ra phn t: Ly ra t u hng i (dequeue)

20

Ci t Queue
public class Queue { private LinkedList queueList; public Queue() { queueList = new LinkedList(); } public void enqueue( int value ) { queueList.insertAtBack( value ); } public int dequeue() { return queueList.removeFromFront(); } public boolean isEmpty() { return queueList.isEmpty(); } public void print() { queueList.print(); }

21

S dng Queue
public class QueueTest { public static void main(String[] args) { Queue queue = new Queue(); queue.enqueue(5); queue.enqueue(7); queue.enqueue(4); queue.enqueue(8); queue.print(); queue.dequeue(); queue.dequeue(); queue.print();

22

Tree
Tree l mt cu trc phi tuyn (non-linear). Mi node trn cy c th c nhiu lin kt ti node khc.
Nt gc

Nt trong

Nt l
23

Binary Search Tree


Cy nh phn l cy m mi node khng c qu 2 node con. Cy tm kim nh phn l cy nh phn m:
Gi tr cc nt thuc cy con bn tri nh hn gi tr ca nt cha. Gi tr cc nt thuc cy con bn phi ln hn gi tr ca nt cha.

Duyt cy nh phn
Inorder traversal Preorder traversal Postorder traversal
24

Binary Search Tree


V d v Binary Search Tree
47
Cy con tri Cy con phi

25 11 7 17 43 31 44 65 68

77 93

25

Ci t Binary Search Tree


public class TreeNode { int data; TreeNode leftNode, rightNode; public TreeNode( int nodeData ) { data = nodeData; leftNode = rightNode = null; } public void insert( int value ) { if ( value < data ) { if (leftNode == null) leftNode = new TreeNode(value); else leftNode.insert( value ); } else if ( value > data ) { if ( rightNode == null ) rightNode = new TreeNode(value); else rightNode.insert( value ); } 26 }

Ci t Binary Search Tree


public class Tree { private TreeNode root; public Tree() { root = null; } public void insertNode( int insertValue ) { if ( root == null ) root = new TreeNode( insertValue ); else root.insert( insertValue ); } public void preorderTraversal() { preorder( root ); }

27

Ci t Binary Search Tree


public void inorderTraversal() { inorder( root ); } public void postorderTraversal() { postorder( root ); } private void preorder( TreeNode node ) { if ( node == null ) return; System.out.print( node.data + " " ); preorder( node.leftNode ); preorder( node.rightNode ); }
28

Ci t Binary Search Tree


private void inorder( TreeNode node ) { if ( node == null ) return; inorder( node.leftNode ); System.out.print( node.data + " " ); inorder( node.rightNode ); } private void postorder( TreeNode node ) { if ( node == null ) return; postorder( node.leftNode ); postorder( node.rightNode ); System.out.print( node.data + " " ); }
29

S dng Binary Search Tree


public class TreeTest { public static void main( String[] args ) { Tree tree = new Tree(); int value; for ( int i = 1; i <= 10; i++ ) { value = ( int ) ( Math.random() * 100 ); tree.insertNode( value ); } System.out.println ( "\n\nPreorder traversal" ); tree.preorderTraversal(); System.out.println ( "\n\nInorder traversal" ); tree.inorderTraversal(); System.out.println ( "\n\nPostorder traversal" ); tree.postorderTraversal();
30

Bi tp ti lp
Bi 1: Dng Stack vit chng trnh in ra dng nh phn ca mt s nguyn dng cho trc. Bi 2: Ci t phng thc search trong lp Tree tm mt phn t c gi tr cho trc.

31

Collection
Collection l i tng c kh nng cha cc i tng khc. Cc thao tc thng thng trn collection
Thm/Xo i tng vo/khi collection Kim tra mt i tng c trong collection khng Ly mt i tng t collection Duyt cc i tng trong collection Xo ton b collection
32

Collections Framework
Cc collection u tin ca Java:
Mng Vector: Mng ng Hastable: Bng bm

Collections Framework (t Java 1.2)


L mt kin trc hp nht biu din v thao tc trn cc collection. Gip cho vic x l cc collection c lp vi biu din chi tit bn trong ca chng.
33

Collections Framework
Mt s li ch ca Collections Framework
Gim thi gian lp trnh Tng cng hiu nng chng trnh D m rng cc collection mi Khuyn khch vic s dng li m chng trnh

34

Collections Framework
Collections Framework bao gm
Interfaces: L cc giao tip th hin tnh cht ca cc kiu collection khc nhau nh List, Set, Map. Implementations: L cc lp collection c sn c ci t cc collection interfaces. Algorithms: L cc phng thc tnh x l trn collection, v d: sp xp danh sch, tm phn t ln nht...

35

Interfaces
<<interface>> Collection <<interface>> Map

<<interface>> Set

<<interface>> List

<<interface>> SortedMap

<<interface>> SortedSet

36

Giao tip Collection


Cung cp cc thao tc chnh trn collection nh thm/xo/tm phn t... V d:
boolean add(Object element); boolean remove(Object element); boolean contains(Object element); int size(); boolean isEmpty();

Nu lp ci t Collection khng mun h tr cc thao tc lm thay i collection nh add, remove, clear... n c th tung ra ngoi l UnsupportedOperationException.
37

Giao tip List


List k tha t Collection, n cung cp thm cc phng thc x l collection kiu danh sch (Danh sch l mt collection vi cc phn t c xp theo ch s). Mt s phng thc ca List
Object get(int index); Object set(int index, Object o); void add(int index, Object o); Object remove(int index); int indexOf(Object o); int lastIndexOf(Object o);
38

Giao tip Set


Set k tha t Collection, h tr cc thao tc x l trn collection kiu tp hp (Mt tp hp yu cu cc phn t phi khng c trng lp). Set khng c thm phng thc ring ngoi cc phng thc k tha t Collection.

39

Giao tip SortedSet


SortedSet k tha t Set, n h tr thao tc trn tp hp cc phn t c th so snh c. Cc i tng a vo trong mt SortedSet phi ci t giao tip Comparable hoc lp ci t SortedSet phi nhn mt Comparator trn kiu ca i tng . Mt s phng thc ca SortedSet:
Object first(); // ly phn t u tin (nh nht) Object last(); // ly phn t cui cng (ln nht) SortedSet subSet(Object e1, Object e2); // ly mt tp cc phn t nm trong khong t e1 ti e2.
40

Duyt collection
Cc phn t trong collection c th c duyt thng qua Iterator. Cc lp ci t Collection cung cp phng thc tr v iterator trn cc phn t ca chng.
Collection c;

Iterator it = c.iterator();

...
41

Duyt collection
Iterator cho php duyt tun t mt collection. Cc phng thc ca Iterator:
boolean hasNext(); Object next(); void remove();

V d:

Iterator it = c.iterator(); while ( it.hasNext() ) { Point p = (Point) it.next(); System.out.println( p.toString() ); }


42

Giao tip Map


Giao tip Map cung cp cc thao tc x l trn cc bng nh x (Bng nh x lu cc phn t theo kho v khng c c 2 kho trng nhau). Mt s phng thc ca Map
Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); ...
43

Giao tip Map


Map cung cp 3 cch view d liu:
View cc kho:
Set keySet(); // Tr v cc kho

View cc gi tr:
Collection values(); // Tr v cc gi tr

View cc cp kho-gi tr
Set entrySet(); // Tr v cc cp kho-gi tr

Sau khi nhn c kt qu l mt collection, ta c th dng iterator duyt cc phn t ca n.


44

Giao tip SortedMap


Giao tip SortedMap k tha t Map, n cung cp thao tc trn cc bng nh x vi kho c th so snh c. Ging nh SortedSet, cc i tng kho a vo trong SortedMap phi ci t giao tip Comparable hoc lp ci t SortedMap phi nhn mt Comparator trn i tng kho.

45

Implementations
Cc ci t trong Collections Framework chnh l cc lp collection c sn trong Java. Chng ci t cc collection interface trn th hin cc cu trc d liu c th. V d: mng ng, danh sch lin kt, cy en, bng bm...

46

Implementations
List LinkedList ArrayList HashSet Set LinkedHashSet SortedSet HashMap Map LinkedHashMap SortedMap TreeMap
47

TreeSet

M t cc ci t
ArrayList: Mng ng, nu cc phn t thm vo vt qu kch c mng, mng s t ng tng kch c. LinkedList: Danh sch lin kt 2 chiu. H tr thao tc trn u v cui danh sch. HashSet: Bng bm. LinkedHashSet: Bng bm kt hp vi linked list nhm m bo th t cc phn t . TreeSet: Cy en (red-black tree).
48

M t cc ci t
HashMap: Bng bm (ci t ca Map). LinkedHashMap: Bng bm kt hp vi linked list nhm m bo th t cc phn t (ci t ca Map). TreeMap: Cy en (ci t ca Map).

49

V d 1: TreeSet
// This program sorts a set of names import java.util.*; public class TreeSetTest1 { public static void main(String[] args) { SortedSet names = new TreeSet(); names.add(new String("Minh Tuan")); names.add(new String("Hai Nam")); names.add(new String("Anh Ngoc")); names.add(new String("Trung Kien")); names.add(new String("Quynh Chi")); names.add(new String("Thu Hang")); System.out.println(names); } }
50

V d 2: Student Set
class Student implements Comparable { private String code; private double score; public Student(String code, double score) { this.code = code; this.score = score; } public double getScore() { return score; } public String toString() { return "(" + code + "," + score + ")"; }
51

V d 2: Student Set
public boolean equals(Object other) { Student otherStu = (Student) other; return code.equals(otherStu.code); } public int compareTo(Object other) { Student otherStu = (Student) other; return code.compareTo(otherStu.code); }

52

V d 2: Student Set
// This programs sorts a set of students by name and then by score import java.util.*; public class TreeSetTest2 { public static void main(String[] args) { SortedSet stu = new TreeSet(); stu.add(new Student("A05726", 8.5)); stu.add(new Student("A06338", 7.0)); stu.add(new Student("A05379", 7.5)); stu.add(new Student("A06178", 9.5)); System.out.println(stu); SortedSet sortByScore = new TreeSet(new Comparator() // create an inner class

53

V d 2: Student Set
{ public int compare(Object a, Object b) { Student itemA = (Student) a; Student itemB = (Student) b; double scoreA = itemA.getScore(); double scoreB = itemB.getScore(); if ( scoreA < scoreB ) return -1; else return 1; } }); // end of inner class

sortByScore.addAll(stu); System.out.println(sortByScore);

54

V d 3: HashMap
// This program stores a phone directory by hashing import java.util.*; public class MyMapTest { public static void main(String[] args) { Map phoneDir = new HashMap(); phoneDir.put("5581814", new String("Dept. Informatics")); phoneDir.put("8584490", new String("Defense Staff")); phoneDir.put("8587346", new String("Administrative Staff")); phoneDir.put("7290028", new String("Student Club")); // print all entries System.out.println(phoneDir); // remove an entry phoneDir.remove("8584490");
55

V d 3: HashMap
// replace an entry phoneDir.put("7290028", new String("International Relation")); // look up a value System.out.println(phoneDir.get("5581814")); // iterate through all entries Set entries = phoneDir.entrySet(); Iterator iter = entries.iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); System.out.println("key=" + key + ", value=" + value); }

56

Cc lp bao
Collection ch lm vic trn cc Object. Nhng kiu d liu c bn nh: byte, short, int, long, double, float, char, boolean khng th a c trc tip vo Collection m phi thng qua cc lp bao. Cc lp bao: Byte, Short, Int, Long, Double, Float, Char, Boolean. V d:
Integer intObject = new Integer(9); int value = intObject.intValue();
57

Algorithms
Cc thut ton c ci t nh nhng phng thc tnh ca lp Collections Mt s phng thc ca Collections:
static Object max(Collection c) static Object min(Collection c) static int binarySearch(List list, Object key) static void sort(List list) static void shuffle(List list) cc phng thc to synchronized collection cc phng thc to read-only collection
58

V d: Trn bi
import java.util.*; public class MyShuffleTest { public static void main(String[] args) { List numbers = new ArrayList(52); for (int i = 1; i <= 52; i++) numbers.add(new Integer(i)); System.out.println("Before shuffling:" + numbers + "\n"); Collections.shuffle(numbers); System.out.println("After shuffling:" + numbers + "\n");

59

Collections Framework
Legacy Implementations
L cc lp c c ci t b sung thm cc collection interface. Vector: C th thay bng ArrayList Hastable: C th thay bng HashMap

Abstract Implementations
L cc lp tru tng ci t cc collection interface m ta c th k tha to ra cc collection mi. AbstractCollection, AbstractSet, AbstractList...
60

Bi tp
1. Ci t cc x l Exception cn thit cho cc phng thc trong LinkedList, Stack, Queue, Tree. 2. Vit chng trnh cho php nhp mt xu k t t bn phm, sau hin th xu ny theo th t ngc li (dng Stack). 3. Vit chng trnh cho php nhp mt danh sch sinh vin sau sp xp danh sch theo th t tng dn. Dng ArrayList v Collections.sort().
61

Bi tp
4. Vit chng trnh h tr tra cu t in n gin. Chng trnh lu cc t v ngha ca t trong mt Collection hoc mt Map. 5. M rng bi tp trn bng cch dng file lu tr cc t. 6. Ci t li Queue t lp ArrayList. 7. Gii cc bi ton ng dng trong mn Cu trc d liu bng cch s dng Collections Framework.
62

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

Bi 9. Multithreading
a nhim v a tuyn To lp v s dng tuyn
Lp Thread Giao tip Runnable

ng b ho cc tuyn Tuyn ma Nhm tuyn Bi tp


2

a nhim (multitasking)
a nhim l k thut cho php nhiu cng vic c thc hin cng mt lc trn my tnh. Nu c nhiu CPU, cc cng vic c th c thc hin song song trn tng CPU. Trong trng hp nhiu cng vic cng chia s mt CPU, tng phn ca mi cng vic s c CPU thc hin xen k.

a nhim (multitasking)

Task 1 Task 2 Task 3

Nhiu cng vic thi hnh trn mt CPU

a nhim (multitasking)
Hai k thut a nhim c bn
a tin trnh (Process-based multitasking): Nhiu chng trnh chy ng thi. Mi chng trnh c mt vng d liu c lp. a tuyn (Thread-based multitasking): Mt chng trnh c nhiu tuyn cng chy ng thi. Cc tuyn dng chung vng d liu ca chng trnh.

Tuyn v a tuyn
Tuyn l mch thi hnh c lp ca mt tc v trong chng trnh. Mt chng trnh c nhiu tuyn thc hin cng lc gi l a tuyn.
program program

To tuyn
Tuyn trong Java cng l cc i tng. C hai cch to tuyn
Tha k t lp java.lang.Thread Ci t giao tip java.lang.Runnable

Cch 1: K tha t Thread


To lp MyThread k tha t Thread v np chng phng thc run() ca lp Thread.

class MyThread extends Thread { . public void run() { } }

To v thc thi tuyn.

Thread th1 = new MyThread(); Thread th2 = new MyThread(); th1.start(); th2.start();

Cch 1: K tha t Thread


Khi mt tuyn c to ra, n cn gi start() t tuyn trng thi sn sng. Tip theo h thng s thc thi cc cu lnh trong run() ca tuyn . Tuyn s kt thc khi lm ht lnh trong run() hoc khi stop() c gi.

To tuyn
To tuyn mi

MyThread th1 = new MyThread(); MyThread th2 = new MyThread(); th1.start(); th2.start();

Sn sng bt u thc thi tuyn


10

Cch 2: Ci t Runnable
Trong trng hp lp k tha t mt lp khc, cn ci t giao tip Runnable lp c th l mt tuyn. Runnable c duy nht mt phng thc run().

class MyClass extends SomeClass implements Runnable { . public void run() { } }

To v thc thi tuyn.

Thread th1 = new Thread(new MyClass()); Thread th2 = new Thread(new MyClass()); th1.start(); th2.start();

11

u tin
Cc tuyn trong Java c u tin t Thread.MIN_PRIORITY (gi tr 1) n Thread.MAX_PRIORITY (gi tr 10) Tuyn c u tin cng cao th cng sm c thc hin v hon thnh. u tin mc nh ca cc tuyn l Thread.NORM_PRIORITY (gi tr 5). Mt tuyn mi s tha k u tin t tuyn to ra n.

12

B lp lch
B lp lch (scheduler) ca Java qun l cc tuyn theo c ch phn chia thi gian (timeslicing). Tng tuyn s c cp mt khong thi gian ngn (time quantum) s dng CPU. Trong khi thc thi, nu ht thi gian c cp th d cha kt thc tuyn cng phi tm dng cho cc tuyn khc cng u tin dng CPU. Cc tuyn cng u tin lun phin s dng CPU theo kiu xoay vng (roundrobin).
13

B lp lch
Priority 10 V d: Tuyn A v B s lun phin nhau thc thi cho n khi kt thc. Tip theo tuyn C s thc thi n khi kt thc. Tip theo tuyn D, E v F s lun phin thc thi n khi kt thc. Tip theo tuyn G thc thi n khi kt thc. Cui cng tuyn H v I lun phin thc thi n khi kt thc. Nhn xt: Cc tuyn c u tin thp s c nguy c b tr hon v hn nh. Priority 9 Priority 8 Priority 7 Priority 6 Priority 5 Priority 4 Priority 3 Priority 2 Priority 1
14

A C

D G

V d v a tuyn
To ra 3 tuyn vi u tin mc nh. Cng vic ca mi tuyn l ng trong mt thi gian ngu nhin t 0 n 5 giy. Sau khi ng xong, cc tuyn s thng bo ra mn hnh.

15

V d v a tuyn
class PrintThread extends Thread { private int sleepTime; public PrintThread( String name ) { super( name ); sleepTime = ( int ) ( Math.random() * 5000); System.out.println( getName() + " have sleep time: " + sleepTime); }

16

V d v a tuyn
// method run is the code to be executed by new thread public void run() { try { System.out.println( getName() + " starts to sleep"); Thread.sleep( sleepTime ); } // sleep() may throw an InterruptedException catch ( InterruptedException e) { e.printStackTrace(); } System.out.println( getName() + " done sleeping" ); } }

17

V d v a tuyn
public class ThreadTest { public static void main( String [ ] args ) { PrintThread thread1 = new PrintThread( "thread1" ); PrintThread thread2 = new PrintThread( "thread2" ); PrintThread thread3 = new PrintThread( "thread3" ); System.out.println( "Starting threads" ); thread1.start(); // start and ready to run thread2.start(); // start and ready to run thread3.start(); // start and ready to run System.out.println( "Threads started, main ends\n" ); } }
18

V d v a tuyn
thread1 have sleep time: 622 thread2 have sleep time: 4543 thread3 have sleep time: 1622 Starting threads Threads started, main ends thread1 thread2 thread3 thread1 thread3 thread2 starts to sleep starts to sleep starts to sleep done sleeping done sleeping done sleeping

19

Mt s phng thc ca Thread


void void void void void void void sleep(long millis); // ng yield(); // nhng iu khin interrupt(); // ngt tuyn join(); // yu cu ch kt thc suspend(); // deprecated resume(); // deprecated stop(); // deprecated

20

Vng i ca tuyn
born

start

read y q uantum exp iratio n


no or n t ify ot i fy Al l

yield
inte rrup t running
it wa

d isp atc h (a ssig n a p roc e ssor)


issu e I/ O re q

I/ O co m p le ti o n

co m

sl ee p

ue s t

et pl e

wa iting

slee ping

de ad

bloc ked

slee p inte rv al expires

21

ng b ho tuyn
Vic cc tuyn trong chng trnh cng truy nhp vo mt i tng c th s em li kt qu khng nh mong mun. V d: Tuyn A cp nht i tng X v tuyn B c d liu t X. Rt c th xy ra s c l tuyn B c d liu cha c cp nht. ng b ho tuyn (thread synchronization) gip cho ti mi thi im ch c mt tuyn c th truy nhp vo i tng cn cc tuyn khc phi i. V d: Trong khi tuyn A cp nht X th tuyn B cha c c.
22

ng b ho tuyn
Dng t kho synchronized trn cc phng thc thc hin ng b ho. i tng khai bo phng thc synchronized s c mt b gim st (monitor). B gim st m bo ti mi thi im ch c mt tuyn c gi phng thc synchronized. Khi mt tuyn gi phng thc synchronized, i tng s b kho. Khi tuyn thc hin xong phng thc, i tng s c m kho.
23

ng b ho Thread
Trong khi thc thi phng thc synchronized, mt tuyn c th gi wait() chuyn sang trng thi ch cho n khi mt iu kin no xy ra. Khi tuyn ang ch, i tng s khng b kho. Khi thc hin xong cng vic trn i tng, mt tuyn cng c th thng bo (notify) cho cc tuyn khc ang ch truy nhp i tng. Deadlock: Tuyn A ch tuyn B v tuyn B cng ch tuyn A.
24

Quan h Producer-Consumer
Gi s c 2 tuyn: Producer ghi d liu vo mt buffer v Consumer c d liu t buffer => Cn c s ng b ho nu khng d liu c th b Producer ghi trc khi Consumer c c hoc Consumer c th c mt d liu nhiu ln khi Producer cha sn xut kp.
Consumer c buffer ghi Producer

25

Quan h Producer-Consumer
Gii php ng b ho:
Trc khi tip tc sinh d liu v a vo buffer, Producer phi ch (wait) Consumer c xong d liu t buffer. Khi Consumer c xong d liu, n s thng bo (notify) cho Producer bit tip tc sinh d liu. Nu Consumer thy trong buffer khng c d liu hoc d liu c c ri, n s ch (wait) cho ti khi nhn c thng bo c d liu mi. Khi Producer sn xut xong d liu, n thng bo (notify) cho Consumer bit.

26

V d v P-C: Khng ng b
class Buffer { private int buffer = -1; public void set( int value ) { buffer = value; } public int get() { return buffer; } }
27

V d v P-C: Khng ng b
class Producer extends Thread { private Buffer sharedBuffer; public Producer( Buffer shared ) { super( "Producer" ); sharedBuffer = shared; }

28

V d v P-C: Khng ng b
public void run() { for ( int count = 1; count <= 5; count++ ) { try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); sharedBuffer.set( count ); System.out.println( "Producer writes " + count); } catch ( InterruptedException e ) { e.printStackTrace(); } } System.out.println( getName() + " finished."); } }
29

V d v P-C: Khng ng b
class Consumer extends Thread { private Buffer sharedBuffer; public Consumer( Buffer shared ) { super( "Consumer" ); sharedBuffer = shared; }

30

V d v P-C: Khng ng b
public void run() { for ( int count = 1; count <= 5; count++ ) { try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); System.out.println( "Consumer reads " + sharedBuffer.get()); } catch ( InterruptedException e ) { e.printStackTrace(); } } System.out.println( getName() + " finished."); } }
31

V d v P-C: Khng ng b
public class SharedBufferTest1 { public static void main( String [] args ) { // create shared object used by threads Buffer sharedBuffer = new Buffer(); // create producer and consumer objects Producer producer = new Producer( sharedBuffer ); Consumer consumer = new Consumer( sharedBuffer ); producer.start(); // start producer thread consumer.start(); // start consumer thread } }
32

Kt qu khi khng ng b
Producer writes 1 Producer writes 2 Consumer reads 2 Producer writes 3 Producer writes 4 Consumer reads 4 Producer writes 5 Producer finished. Consumer reads 5 Consumer reads 5 Consumer reads 5 Consumer finished.

33

V d v P-C: C ng b
class Buffer // Thit k li lp Buffer { private int buffer = -1; private boolean writable = true; public synchronized void set( int value ) { while ( ! writable ) { try { wait(); } catch ( InterruptedException e ) { e.printStackTrace(); } } buffer = value; writable = false; notify(); }

34

V d v P-C: C ng b
public synchronized int get() { while ( writable ) { try { wait(); } catch ( InterruptedException e ) { e.printStackTrace(); } } writable = true; notify(); return buffer; } }
35

Kt qu khi c ng b
Producer writes 1 Consumer reads 1 Producer writes 2 Consumer reads 2 Producer writes 3 Consumer reads 3 Producer writes 4 Consumer reads 4 Producer writes 5 Producer finished. Consumer reads 5 Consumer finished.

36

To tuyn t giao tip Runnable


Mt lp c th tr thnh mt tuyn khi ci t giao tip Runnable (giao tip ny ch c mt phng thc run() duy nht). V d: To applet c qu bng chy

37

To tuyn t giao tip Runnable


import java.awt.*; import java.applet.*; public class BallFlying extends Applet implements Runnable { Thread animThread = null; int ballX = 0, ballY =50; int dx=1, dy=2; boolean stopRun = false; public void start() { // applet starts if (animThread == null) { animThread = new Thread(this); animThread.start(); } }
38

To tuyn t giao tip Runnable


public void stop() { // applet stops stopRun = true; } public void run() { this.setBackground(Color.CYAN); while (! stopRun) { moveBall(); delay(5); } } private void delay(int miliSeconds) { try { Thread.sleep(miliSeconds); } catch (Exception e) { System.out.println("Sleep error !"); } }

39

To tuyn t giao tip Runnable


private void moveBall() { ballX+=dx; ballY+=dy; if (ballY > getSize().height - 30) if (ballX > getSize().width - 30) if (ballY < 0) dy=-dy; if (ballX < 0) dx=-dx; repaint(); } public void paint(Graphics g) { g.fillOval(ballX,ballY, 30, 30); } }
40

dy=-dy; dx=-dx;

Kt qu thc thi

41

Tuyn ma (daemon thread)


Tuyn ma thng l tuyn h tr mi trng thc thi ca cc tuyn khc. V d: garbage collector ca Java l mt tuyn ma. Chng trnh kt thc khi tt c cc tuyn khng phi tuyn ma kt thc. Cc phng thc vi tuyn ma:
void setDaemon(boolean isDaemon); // t tuyn tr thnh tuyn ma boolean isDaemon(); // kim tra tuyn c phi tuyn ma khng
42

Nhm tuyn (thread group)


Cc tuyn c th c a vo trong cng mt nhm thng qua lp ThreadGroup. V d: nhm tuyn tm kim d liu trn cc tp d liu khc nhau. Mt nhm tuyn ch c th x l trn cc tuyn trong nhm, v d: ngt tt c cc tuyn. C th to ra cc nhm tuyn l nhm con ca mt nhm tuyn khc. Nhm tuyn c bit: system, main

43

Lp Timer
Hai lp lin quan ti x l cng vic

theo thi gian

javax.swing.Timer java.util.Timer

Lp java.swing.Timer
n gin, d dng trn GUI

Lp java.util.Timer
Nhiu tnh nng hn java.swing.Timer

44

V d: m ngc
import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class CountDown extends Applet implements ActionListener { private TextField timeField; private Button startButton; private Button stopButton; private javax.swing.Timer timer; private int count; public void init() { timeField = new TextField(6); timeField.setFont(new Font("sansserif", Font.PLAIN, 18)); startButton = new Button("Start"); stopButton = new Button("Stop");
45

V d: m ngc
add(timeField); add(startButton); add(stopButton); startButton.addActionListener(this); stopButton.addActionListener(this); timer = new javax.swing.Timer(10, this); count = 0; } // end init()

46

V d: m ngc
public void actionPerformed(ActionEvent e) { if ( e.getSource() == startButton) timer.start(); else if (e.getSource() == stopButton) timer.stop(); else { count++; int hsecond = count%100; int totalSecond = (count/100); int h = totalSecond/3600; int secondLeft = totalSecond%3600; int m = secondLeft/60; int s = secondLeft%60; timeField.setText(" + h + ":" + m + ":" + s + ":" + hsecond); } }
47

Bi tp
1. S dng k thut khung hnh ph ci tin chng trnh v bng. 2. M rng chng trnh v bng cho php hai qu bng cng chy trn mn hnh vi tc khc nhau (Xem li bi v Graphics). 3. M rng chng trnh v bng cho php trong khi bng chy, nu ngi dng click chut vo mt v tr no trn mn hnh th bng s c chuyn ra v tr .

48

Bi tp
4. Mt k thut hot hnh khc l xem mi i tng chuyn ng nh mt tuyn c lp, v d: qu bng. Tuyn chnh ca chng trnh s lin tc ly d liu t qu bng th hin ra mn hnh (paint() v repaint()) trong khi tuyn qu bng s thc hin chuyn ng thng qua vic thay i gi tr to ca n. Vit chng trnh xy dng lp Ball k tha t lp Thread v t to cc qu bng di chuyn trn mn hnh.
49

Bi tp
5. Vit chng trnh to 2 tuyn: mt tuyn tm kim cc s nguyn t t 1000 n 1000000 v mt tuyn tnh tng gi tr ca cc s nguyn t tm c. Ch ng b tuyn. 6. Vit chng trnh to mng c 1000000 phn t, sau to 2 tuyn sp xp 2 na mng, cui cng ghp 2 mng sp xp. So snh cch lm trn vi cch sp xp trc tip ton b mng.
50

Bi tp
7. Mt vn vi Producer-Consumer l nu vic tiu th chm hn vic sn xut th Producer s phi i Consumer. Hy thit k li v d hc cho php buffer c th lu cng lc 5 gi tr (dng mng), v Producer c th ghi vo buffer ny cho n khi y mi phi i. 8. M rng chng trnh trn vi buffer l mt hng i (FIFO).

51

You might also like