Professional Documents
Culture Documents
Lp trnh Java c bn
Nam 2007
Trang 1
http://www.ebook.edu.vn
Lp trnh Java
Trang 2
http://www.ebook.edu.vn
Lp trnh Java
- Java yu cu cht ch v kiu d liu v phi m t r rng khi vit chng trnh. Chng s kim tra lc bin dch v c trong thi gian thng dch v vy Java loi b cc kiu d liu d gy ra li.
- J2SE (Java 2 Standard Edition) va l mt c t, cng va l mt nn tng thc thi (bao gm c pht trin v trin khai) cho cc ng dng Java. N cung cp cc API, cc kin trc chun, cc th vin lp v cc cng c ct li nht xy dng cc ng dng Java. - J2SE gm 2 b phn chnh l: Java 2 Runtime Environment, Standard Edition (JRE) Java 2 Software Development Kit, Standard Edition (SDK). - Mi trng thc thi hay JRE cung cp cc Java API, my o Java v cc thnh phn cn thit khc chy cc Applet v ng dng vit bng ngn ng lp trnh Java. Mi trng thc thi Java khng c cc cng c v tin ch nh l cc trnh bin dch hay cc trnh g li pht trin cc applet v cc ng dng. - Java 2 SDK l mt tp m ca JRE, v cha mi th nm trong JRE, b sung thm cc cng c nh l trnh bin dch v cc trnh g li cn pht trin applet v cc ng dng.
Trang 3
http://www.ebook.edu.vn
Lp trnh Java
2) Cng ngh Java: Hin nay, Java c 3 cng ngh: - J2SE (Java 2 Standard Edition): cng ngh Java chun dnh cho hu ht mi trng pht trin ng dng Java. - J2EE (Java 2 Enterprise Edition): cng ngh Java dnh cho mi trng x nghip (Enterprise) h tr kin trc Web, EJB, Transaction, Database... - J2ME (Java 2 Micro Edition): cng ngh pht trin cc ng dng cho thit b iu khin nh gia dng, in thoi di ng,...
Trang 4
http://www.ebook.edu.vn
Lp trnh Java
- Cha trnh bin dch v cc cng c h tr. - Cha cc chng trnh mu. - Cha cc tp tin bin dch native code - Mi trng thc thi ng dng java. - Cha nhng tp tin th vin .jar - Cc chng trnh mu n gin.
3) Cc tp tin bin dch thng dng: a) Javac: - Dng bin dch chng trnh m ngun (.java) thnh tp tin byte code (.class) $javac filename.java b) Java: - Trnh thng dch java, dng thi hnh chng trnh java application $java filename
c) Appletviewer: - Trnh duyt applet, dng thi hnh chng trnh java applet $appletview filename.html
Trang 5
http://www.ebook.edu.vn
Lp trnh Java
Trang 6
http://www.ebook.edu.vn
Lp trnh Java
1) Chng trnh ng dng console: Yu cu: Chng trnh hin th dng ch Welcome to Java program. Thc hin: - Bc 1: To tp tin java ngun Welcome.java (s dng chng trnh NotePad)
class Welcome{ //main method public static void main(String args[]){ //display the string System.out.println("\n Welcome to Java program"); } }
- Bc 2: Bin dch tp tin ngun. Chn Start -> Run v nhp lnh cmd.
Chuyn n th mc cha tp tin ngun cn bin dch. Dng lnh javac bin dch tp tin ngun.
D:\Lab1\javac Welcome.java
Trang 7
http://www.ebook.edu.vn
Lp trnh Java
Kt qu chng trnh console 2) Chng trnh Java Applet: Yu cu: - Chng trnh v chui Welcome to Java Programming ra ca s applet. Thc hin: - Bc 1: To tp tin java ngun WelcomeApplet.java.
import java.awt.Graphics; import javax.swing.JApplet; public class WelcomeApplet extends JApplet{ public void paint(Graphics g){ super.paintComponents(g); g.drawString( "Welcome to Java Programming!",25,25); } }
Trang 8
http://www.ebook.edu.vn
Lp trnh Java
Kt qu chng trnh s dng applet Ta c th xem applet bng trnh duyt Web.
Trang 9
http://www.ebook.edu.vn
Lp trnh Java
Trang 10
Lp trnh Java
th kiu int l 4 bytes. Nhng i vi Java, kch thc ca tt c kiu d liu l c lp h nn. 1) Cc kiu d liu nguyn thy (primitive): a) Kiu s (nguyn, thc):
Kiu Kch thc Min gi tr
2.147.483.648 2.147.483. 647 32.768 32.767 9.223.372.036.854.775.808 9.223.372.036.854.775.807 128 127 3.40282347E+38F 1.79769313486231570E+308
b) Kiu k t (char): - Kch thc 2 byte. c) Kiu lun l (boolean): - Kiu boolean c 2 gi tr true. false Ch : - Trong java khng c kiu unsigned 2) Cc kiu d liu tham chiu (reference): - Trong Java c 3 kiu d liu tham chiu:
Kiu d liu Mng (Array) Lp (Class) Giao din (Interface) Min gi tr Tp hp cc d liu cng loi. Tp hp cc bin v cc phng thc. L mt lp tru tng c to ra b sung cho cc k tha a lp trong Java.
Trang 11
Lp trnh Java
Khai bo bin:
<kiu d liu> <tn_bin>;
V d: int float 2) Hng: - Vng nh lu tr tm thi d liu x l. Hng c gi tr khng i. Khai bo hng:
final <kiu d liu> <tn hng>=<gi tr>;
x; a. b=6;
c bit: php ton + cn dng vi ngha ni chui. - Number + String -> String - Boolean + String -> String V d: System.out.println( Hello + World!); // Kt qu in trn mn hnh: Hello World!
Trang 12
http://www.ebook.edu.vn
Lp trnh Java
V d: int x=5; System.out.println(Value x = + x); // Kt qu in trn mn hnh: Value x=5 2) Chuyn kiu trong java: - Chuyn s nguyn sang s thc v ngc li: V d: int n=5; double x; x=n; System.out.println(d); //kt qu in trn mn hnh: 5.0 V d: double int n; n=(int) x; System.out.println(n); // Kt qu in ra mn hnh: 15 - Chuyn d liu chui sang s: s dng cc phng thc ca cc lp bao kiu s (Integer. Long. Float. Double...) Integer.parseInt(chui dng s nguyn) Float.parseFloat(chui dng s thc) Double.parseDouble(chui dng s thc) V d: Int n; n= Integer.parseInt(12); // n c gi tr l 12 V d: double x; x= Double.parseDouble(12.25); // n c gi tr l 12.25 x=15.7;
Trang 13
http://www.ebook.edu.vn
Lp trnh Java
V d: import java.util.*; public class InputTest{ public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.print("What is your name? "); String name = in.nextLine(); System.out.print("How old are you? "); int age = in.nextInt(); // display output on console System.out.println("Hello. "+ name + ". Next year. you'll be " +(age + 1)); } }
Trang 14
http://www.ebook.edu.vn
Lp trnh Java
Ch : - Nu s dng phin bn trc JDK1.5.0. ta s rt kh khn c gi tr t ngi dng ch console. Phng php n gin l nn s dng hp thoi (JOptionPane). Vi lnh nh sau:
String input = JOptionPane.showInputDialog(Thng bo);
- Kt qu nhn c l kiu chui. chuyn d liu sang kiu s ta dng phng thc chuyn kiu: Integer.parseInt hoc Double.parseDouble V d: import javax.swing.*; public class InputTest{ public static void main(String[] args){ String name = JOptionPane.showInputDialog("What is your name?"); String input = JOptionPane.showInputDialog("How old are you?"); int age = Integer.parseInt(input); JOptionPane.showMessageDialod(null."Hello. " + name + ". Next year. you'll be " +(age + 1)); System.exit(0); } }
Lp trnh Java
b) Khi lnh: - L tp hp nhiu lnh nm trong mt cp mc { v } V d: { int } 3) Cu lnh iu kin: a) Cu lnh if ..else: Dng 1 (if thiu): if(<biu thc iu kin>) { <lnh 1> <lnh 2> } Dng 2 (if thiu): if(<biu thc iu kin>) { <lnh 1-1> <lnh 1-2> } else { <lnh 2-1> <lnh 2-2> } Dng 3 (if m rng): if(<biu thc iu kin 1>) { <lnh 1-1> <lnh 1-2> } elseif(<biu thc iu kin 2>) { <lnh 2-1> <lnh 2-2> } else { <lnh 3-1> <lnh 3-2> ... } x =5; // lnh 1 System.out.println(Gi tr x= +x); // lnh 2
Trang 16
http://www.ebook.edu.vn
Lp trnh Java
V d: - Chng trnh sau kim tra xem s nguyn c nhp vo t bn phm l s chn hay l v hin th thng bo ph hp. import java.util.Scanner; public class CheckNumber{ public static void main(String args[]){ Scanner in = new Scanner(System.in); System.out.print(Input a integer value:); int num = in.nextInt(); if(num %2 == 0) System.out.println(num + is an even number); else System.out.println(num + is an odd number); } }
Kt qu ca chng trnh CheckNumber b) Cu lnh switch: C php: switch(<biu thc>) { case <gi tr 1>: case <gi tr 2>: default:
Lu : - Biu thc trong cu lnh switch phi c gi tr kiu nguyn (byte,char) V d: - Chng trnh sau kim tra ngy hin ti l th my trong tun.
Trang 17
http://www.ebook.edu.vn
Lp trnh Java
import java.util.Date; class DateTest{ public static void main(String agrs[]){ Date today = new Date(); int day = today.getDay(); switch(day){ case 0: System.out.println("Today is Sunday"); break; case 1: System.out.println("Today is Monday"); break; case 2: System.out.println("Today is Tuesday"); break; case 3: System.out.println("Today is Wednesday"); break; case 4: System.out.println("Today is Thursday"); break; case 5: System.out.println("Today is Friday"); break; case 6: System.out.println("Today is Satuday"); break; default: System.out.println("Invalid day of week"); } } }
Trang 18
http://www.ebook.edu.vn
Lp trnh Java
4) Cu trc vng lp: a) Vng lp while: C php: while(<biu thc iu kin>){ <lnh 1>; <lnh 2>; } b) Vng lp do..while: C php: do{ <lnh 1>; <lnh 2>; }while(<biu thc iu kin>); c) Vng lp for: C php: for(<khi to>;<Bthc iu kin>;<Bthc thay i>){ <lnh 1>; <lnh 2>; } V d: public class LoopTest{ public static void main(String args[]){ listNums1(3); listNums2(4); listNums3(5); } // while loops public static void listNums1(int max){ int i=0; while(i<=max){ System.out.println("Number: " + i); i++; } } // do loops
Trang 19
http://www.ebook.edu.vn
//i=i+1;
Lp trnh Java
public static void listNums2(int max){ int i=0; do{ System.out.println("Number: " + i); i++; }while(i<=max); } // for loops public static void listNums3(int max){ for(int i=0;i<max;i++){ System.out.println("Number: " + i); } } }
Kt qu chng trnh LoopTest.java 5) Cu lnh break, continue v return: a) Lnh break: - Khi gp lnh break, chuong trnh s di chuyn iu khin ra khi khi lnh.
Trang 20
http://www.ebook.edu.vn
Lp trnh Java
V d: int i = 1; while(true){ if(i == 3) break; System.out.println(i); i++; } <Lnh k> - Khi i = 3 th chng trnh thot khi vng lp v thc hin lnh k. b) Lnh continue: - Di chuyn iu khin sang ln lp k tip v khng thc hin lnh ng sau n. V d: for(i=0; i<5; i++){ if(i%2 == 0) continue; System.out.println(i); } - Khi i = s chn th chng trnh s khng thc hin lnh in i m thc hin tip vng lp k. c) Lnh return: - Chm dt s thc thi ca mt phng thc v tr v gi tr cho li gi phng thc. C php: return; Hoc return <gi tr>;
VII.
MNG (Array):
Mng l mt cu trc d liu m n lu tr tp hp cc phn t c gi tr cng kiu. Ta truy xut 1 phn t ca mng thng qua tn mng v ch s (index) ca n. 1) Mng 1 chiu: Khai bo: <kiu d liu> <tn mng>[];
Trang 21
http://www.ebook.edu.vn
Lp trnh Java
Int a[]; Int b[]=new int[10]; // va khai bo va cp pht int c[] ={2,3,5,7,11,13}; // va khai bo v khi to - Ch s phn t ca mng xut pht t 0 kch_thc - 1 - bit s phn t ca mng, dng phng thc length V d: for(int i = 0; i < a.length; i++) System.out.println(a[i]); - Trong JDK1.5. ta c th dng vng lp for each duyt tp hp (mng). C php: for(<bin>:<tp_hp>){ <lnh 1>; <lnh 2>; } V d: for(int x:a) System.out.println(x); V d: - Nhp mng s nguyn c n phn t bng console windows. Tnh tng mng va nhp. import java.util.Scanner; public class ArrayTest{ public static void inputArray(int a[], Scanner in){ for(int i=0;i<a.length;i++){ System.out.print("Input a["+i+ "]:"); a[i]=in.nextInt(); } } public static void outputArray(int a[]){ for(int i=0;i<a.length;i++){ System.out.print(a[i] + " } } public static int sumArray(int a[]){ int s=0; for(int i=0;i<a.length;i++){
Trang 22
http://www.ebook.edu.vn
");
Lp trnh Java
s+=a[i]; } return s; } public static void main(String args[]){ int a[],n; Scanner in = new Scanner(System.in); System.out.print("Input the elements of the array:"); n= in.nextInt(); a= new int[n]; inputArray(a.in); System.out.println("\n----------------------------"); System.out.print("Array is:"); outputArray(a); System.out.println("\n----------------------------"); System.out.println("Sum of the array:" +sumArray(a)); System.out.println("----------------------------"); } }
Kt qu chng trnh ArrayTest.java 2) Mng 2 chiu: Khai bo: <kiu d liu> <tn mng>[][];
Trang 23
http://www.ebook.edu.vn
Lp trnh Java
Cp pht vng nh: <tn mng> = new <kiu d liu>[s dng][s ct]; V d: int a[][]; a= new int [3][3]; int b[][]= new int [3][2]; // khai bo v cp pht int array[] ={{16, 3, 2, 13}, {5, 10, 11, 8}, {9, 6, 7, 12}}; - Truy xut phn t dng i. ct j ca mng: b[i][j] Duyt mng 2 chiu: V d: for(int row = 0;row < array.length;row++){ for(int col = 0;col < array[row].length;col++){ System.out.println( } System.out.println(\n); } - Dng vng lp for each duyt mng 2 chiu: for(int[] row:array){ for(int x:row){ <lnh 1>; <lnh 2>; } } + array[row][col]);
VIII. GI (package):
1) Khi nim: Gi l th mc cha mt hay nhiu tp tin .class sau khi bin dch t tp tin m ngun (.java) nhm mc ch phn phi cho ngi dng khc s dng li. Gi c tnh phn cp (gi lng gi). u im ca vic to gi: - Cho php t chc cc lp vo nhng n v nh hn - Gip trnh c tnh trng trng lp khi t tn. - Cho php bo v cc lp i tng - Tn gi (Package) c th c dng nhn dng chc nng ca cc lp.
Trang 24
http://www.ebook.edu.vn
Lp trnh Java
Mt s gi chun ca java: - java.lang - java.applet - java.awt - javax.swing - java.io - java.util - java.net - java.awt.event - java.rmi - java.security - java.sql 2) To gi: t mt lp vo gi. t lnh to gi vo dng u ca tp tin m ngun C php: package <tn_gi>; V d: package my.com; public class Common{ public static boolean evenCheck(int x){ if(x%2==0) return true; return false; } } 3) S dng li lp trong gi: Mt chng trnh .java mun s dng mt lp ci t. ta phi nhp lp ny u chng trnh (ging nh include tp tin .h trong C). C php: import <tn_gi>.<tn_lp>; import <tn_gi>.*; V d: import my.com.Common; public class CommonTest{ public static void main(String args[]){
Trang 25
http://www.ebook.edu.vn
Lp trnh Java
int x=4; System.out.println("Even x test:" + Common.evenCheck(x)); } } Lu : - Dng lnh khai bo to gi phi l dng u tin trong tp tin khai bo lp. - Cc tp tin khai bo lp trong cng gi phi c lu trong cng mt th mc. - Khng nn tham kho ton b mt gi v s lm tn b nh trong khi ch truy cp n mt vi lp trong gi.
Trang 26
http://www.ebook.edu.vn
Lp trnh Java
I. KHI NIM:
1) Khi nim lp trnh hng i tng - Lp trnh hng i tng (OOP) l mt phng php thit k v pht trin phn mm. Nhng ngn ng OOP khng ch bao gm c php v mt trnh bin dch (compiler) m cn c mt mi trng pht trin ton din. Mi trng ny bao gm mt th vin c thit k tt, thun li cho vic s dng cc i tng. - Trong OOP, mi vn c chia ra thnh nhiu yu t, c gi l cc i tng (Objects) hoc cc Thc th (Entities). - Chng ta s dng k thut hng i tng nh x nhng thc th chng ta gp phi trong i sng thc thnh nhng thc th tng t trong my tnh. 2) c im ca lp trnh hng i tng: S ng gi (Encapsulation): L vic gom chung d liu v cc thao tc lin quan n d liu thnh mt th thng nht, trnh c cc thao tc khng hp l t bn ngoi. Tnh k tha (Inheritance): Mt lp mi c th xy dng t mt lp c thng qua s k tha. S k tha c th l k tha d liu v cc phng thc. Tnh a hnh (Polymorphism): Tnh a hnh cho php m t nhng phng thc c tn ging nhau trong cng mt lp hoc trong cc lp khc nhau. Ni cch khc, mt thao tc c th c ci t khc nhau trong cng mt lp hay trong nhng lp khc nhau.
Lp trnh Java
b) i tng di gc lp trnh: i tng = thuc tnh + phng thc 2) Lp (Class): L cu trc m t cho cc i tng cng cc tnh cht c trng. Lp phi ch ra thnh phn thuc tnh v cc phng thc ca i tng thuc lp. a) nh ngha lp: C php:
[modifier] class ClassName{ modifier data-type field1; modifier data-type field2; ... modifier data-type fieldN;
Cc thuc tnh lp
//Constructor Cc phng thc lp modifier ClassName(cparams1){ // body of constructor } ... modifier ClassName( cparams2){ // body of constructor } //Method modifier return-type methodName1(parameters){ // body of method } ... modifier return-type methodName2(parameters){ // body of method } }
V d: nh ngha lp Circle (hnh trn) package shape; public class Circle{ // khai bo thnh phn thuc tnh private double radius; // nh ngha Constructor public Circle(){ radius=1.0; } public Circle(double r){
Trang 28
http://www.ebook.edu.vn
Lp trnh Java
radius=r; } //nh ngha phng thc //cp nht gi tr cho thuc tnh radius public void setRadius(double r){ radius=r; } // c gi tr ca thuc tnh radius public double getRadius(){ return radius; } // tnh din tch public double area(){ return radius*radius*Math.PI; } // tnh chu vi public double perimeter(){ return 2*radius*Math.PI; } // phng thc chnh public static void main(String args[]){ Circle myCircle = new Circle(); myCircle.setRadius(3.0); System.out.println("Radius is:" + myCircle.getRadius()); System.out.println("Area of circle is:" + myCircle.area()); System.out.println("Perimeter of circle is:" + myCircle.perimeter()); } }
Trang 29
http://www.ebook.edu.vn
Lp trnh Java
Kt qu ca Circle.java 3) Khai bo v s dng i tng: Mt khi lp c nh ngha, ta c th d dng khai bo bin (i tng) ca lp theo c php sau: <ClassName <objectName>; V d: Color blue; Point start; - Gi tr m i tng tham chiu ban u l null. - Trc khi s dng i tng, cn phi khi to i tng bng ton t new C php: objectName = new ClassName(); V d: start = new Point(2,3); Truy xut thnh phn ca i tng: - Truy xut thnh phn d liu: objectName.fieldName V d: Lp Point trong java c 2 thuc tnh x v y. Ta c th truy xut nh sau: Point p = new Point(2,3); int xSquared = p.x * p.x; // xSquared c gi tr 4 int xPlusY = p.x + p.y; // xPlusY c gi tr 5 p.x = 7; xSquared = p.x * p.x; // xSquared c gi tr 49 - Truy xut (gi) thnh phn phng thc: variableName.methodName(param); V d: String s = new String(Hello Word); int len = s.length(); // len c gi tr 10
Trang 30
http://www.ebook.edu.vn
Lp trnh Java
int
4) Phng thc: a) Phng thc: Phng thc l nhng ng x ca lp ln cc thnh phn d liu hay ln cc tc ng bn ngoi. Phng thc c nh ngha theo cu trc sau:
[modifier] <kiu_tr_v> <tn_phng_thc>([cc tham s]){ // thn ca phng thc }
Mt phng thc c cc tnh cht b t (modifiers) nh: - public: c th truy cp t bn ngoi lp nh ngha - protected: ch c truy cp t lp nh ngha v nhng lp dn xut ca lp . - private: ch c truy cp trong bn thn lp nh ngha. - static: mt phng thc ca lp, chung cho mi phin bn ca lp. - abstract: khng c ci t g trong lp. - final: khng b nh ngha chng (overriding) cc lp dn xut . - synchronized: dng ch mt phng thc ti hn, ngn cc tc ng ca i tng khc ln i tng trong khi vic ng b ha ang thc hin. b) Constructor: - Cn gi l phng thc khi to. - Constructor l mt phng thc c bit c gi t ng khi chng trnh to mt i tng mi vi ton t new. - Phng thc Constructor phi c cng tn vi lp v khng khai bo kiu tr v. - Phng thc Constructor gn cc gi tr ban u cho thuc tnh ca i tng v cc cng vic cn thit trc khi a i tng vo hot ng. V d: nh ngha lp Employee class Employee{ // instance fields private String name; private double salary; private int age; // constructor public Employee(String n, double s, int y){ name = n; salary = s; age = y; } // method
Trang 31
http://www.ebook.edu.vn
Lp trnh Java
public void raiseSalary(double byPercent){ double raise = salary * byPercent / 100; salary += raise; } public String toString(){ return "Name:" + name + "\nSalary:" + salary + "\nAge:" + age; } } // end class Employee public class TestEmployee{ public static void main(String args[]){ Employee } } emp = new Employee("James",750,35); System.out.println(emp.toString());
Kt qu ca TestEmployee.java Ch : - Nu mt lp khng c constructor, Java s gn cho n mt constructor mc nh. l khi to tt c thnh phn d liu ca lp theo cc gi tr mc nh ca kiu d liu tng ng. Tuy nhin iu rt nguy him v thiu thn trng. Do ta lun phi xc nh mt constructor cho mi lp to. c) T kha this: - Mi lp trong java lun tn ti mt bin n this. - Thnh phn ny c s dng trong khi chy v tham kho n bn thn lp cha n.
Trang 32
http://www.ebook.edu.vn
Lp trnh Java
V d: // nh ngha constructor cho lp Employee public Employee(String name, double salary, int age){ this.name = name; this.salary = salary; this.age = age; } Trong v d trn do cc tn bin tham s cng tn vi cc d liu ca lp d hiu khi s dng. Trong trng hp ny, ta phn bit c d liu ca lp nh dng bin this. 5) Khai bo chng phng thc (overloaded method): - Khai bo chng phng thc l ta to ra nhiu phng thc c cng tn, cc phng thc ch khc nhau cc tham s. - Do khi gi mt phng thc c khai bo chng, ta phi xc nh ng tham s cn gi theo phng thc tng ng thc hin. V d: - nh ngha lp Point3D class Point3D{ double x; double y; double z; Point3D(double x){ this(x,0,0); } Point3D(double x, double y){ this(x,y,0); } Point3D(double x, double y, double z){ this.x = x; this.y = y; this.z = z; }
Cc phng thc Contructor chng nhau.
Trang 33
http://www.ebook.edu.vn
Lp trnh Java
void move(double x, double y, double z){ this.x = x; this.y = y; this.z = z; } void move(double x, double y){ this.x = x; this.y = y; } void move(double x){ this.x = x; } } - S dng lp Point3D class Point3DTest{ public static void main(String args[]){ Point3D p = new Point3D(1.1, 3.4, -2.8); p.move(5); System.out.println(p.x = + p.x); System.out.println(p.y = + p.y); System.out.println(p.z = + p.z); p.move(6,6); System.out.println(p.x = + p.x); System.out.println(p.y = + p.y); System.out.println(p.z = + p.z); p.move(7,7,7); System.out.println(p.x = + p.x); System.out.println(p.y = + p.y); System.out.println(p.z = + p.z); } }
Cc phng thc move chng nhau.
Trang 34
http://www.ebook.edu.vn
Lp trnh Java
Kt qu chng trnh Point3DTest 6) D liu lp v phng thc lp (static): a) D liu lp: - L d liu dng chung (ton cc) cho tt c cc i tng cng kiu lp. Khai bo: static <kiu> <tnbin>; V d: class Aclass{ static int a; int b; ... } Aclass x = new Aclass(); Aclass y = new Aclass();
i tng x a b i tng y
a b
- Thc hin gn gi tr: x.a = 10; x.b = 20; y.a = 30; y.b = 40; - Kt thc 4 cu lnh trn ta c x.a = 30 , x.b = 20
Trang 35
http://www.ebook.edu.vn
Lp trnh Java
b) Phng thc lp: - L phng thc c trng khng cn truy cp d liu phin bn (non-static) ca lp. - Phng thc lp thng tng t nh hm ton cc trong cc ngn ng khc. - Phng thc lp ch truy xut d liu ton cc (static). C php: public static <tn phng thc>([cc tham s]){ // thn ca phng thc } - truy xut phng thc lp ca lp, ta dng c php sau: <ClassName>.<methodName>([params); V d: class Bclass{ static int a; int b; public static void f1(){ a++; // Truy xut hp l b++; // Pht sinh li } public void f2(){ b++; } } - Thc hin gi phng thc tnh: Bclass.f1(); Bclass.f2(); // Pht sinh li v f2 khng l static
Trang 36
http://www.ebook.edu.vn
Lp trnh Java
1) nh ngha lp k tha: C php: [modifier] class <Lp Con> extends <Lp Cha>{ // khai bo d liu mi ... // nh ngha phng thc mi ... } - Tt c cc lp khi nh ngha trong java u l lp dn xut t lp Object mc nh ca Java. Nhng ta c th b qua khai bo extends Object trong khi vit chng trnh (y l dng k tha ngm nh). V d: - Xt quan h gia lp Cylinder (hnh tr) v lp Circle (hnh trn). Nu c lp Circle, mun nh ngha lp Cylinder, ta d dng nhn thy rng Cylinder l hnh nh c bit ca Circle. Do ta c th dn xut t lp Circle nh ngha lp Cylinder.
Circle radius: double setRadius(double):void getRadius (): double area (): double perimeter (): double
Cylinder length: double setLength(double):void getLength (): double volume (): double
M hnh UML - Lp Circle.java package shape; public class Circle{ // Khai bo thnh phn thuc tnh private double radius; // Constructor public Circle(){
Trang 37
http://www.ebook.edu.vn
Lp trnh Java
radius=1.0; } public Circle(double r){ radius=r; } // Cp nht gi tr cho thuc tnh radius public void setRadius(double r){ radius=r; } // c gi tr ca thuc tnh radius public double getRadius(){ return radius; } // tnh din tch public double area(){ return } // tnh chu vi public double perimeter(){ return 2*radius*Math.PI; } } - Lp Cylinder.java package shape; import java.text.DecimalFormat; public class Cylinder extends Circle{ // Khai bo d liu mi private double length; // Constructors public Cylinder(){ super(); length=1.0; } public Cylinder(double radius,double length){ super(radius);
Trang 38
http://www.ebook.edu.vn
radius*radius*Math.PI;
Lp trnh Java
this.length=length; } // cp nht gi tr thuc tnh length public void setLength(double length){ this.length=length; } // c gi tr thuc tnh length public double getLength(){ return length; } // tnh th tch public double volume(){ return super.area()*length; } // phng thc chnh public static void main(String args[]){ Cylinder cyl = new Cylinder(2.0,3.0); DecimalFormat fmt = new DecimalFormat("0.00"); System.out.println(Radius of cylinder: + cyl.getRadius()); System.out.println(Length of cylinder: + cyl.getLength()); System.out.println(Volumn of cylinder: + fmt.format(cyl.volume())); } }
Kt qu ca Cylinder.java
Trang 39
http://www.ebook.edu.vn
Lp trnh Java
2) T kha super: T kha super dng tham chiu n lp cha ca lp ang xt tng t nh t kha this l mt tham chiu n bn thn lp ang xt. C php:
super([params]) //gi Contructor lp cha super.<methodName>([params]) //gi phng thc lp cha
3) nh ngha li phng thc (Orverriding method) Do tnh tha k, lp con nhn tt c cc phng thc public hay protected ca lp cha lm ca mnh v cng c th thay th cc phng thc ny nu thy cn thit bng cch khai bo chng. V d: - Trong v d trn, do tnh k tha, lp Cylinder nhn phng thc area () ca lp Circle l phng thc ca mnh, nhng trong ng cnh lp Cylinder, cch x l ca phng thc area () khng cn ph hp, khi lp Cylinder c th khai bo chng phng thc area () ca lp cha n nh sau: - Lp Circle.java package shape; public class Circle{ // khai bo thnh phn thuc tnh private double radius; ... // tnh din tch public double area(){ return } // tnh chu vi public double perimeter(){ return 2*radius*Math.PI; } } - Lp Cylinder.java package shape; import java.text.DecimalFormat; public class Cylinder extends Circle{ // khai bo d liu mi private double length;
Trang 40
http://www.ebook.edu.vn
radius*radius*Math.PI;
Lp trnh Java
... // nh ngha li phng thc area() public double area(){ return } // tnh th tch public double volume(){ return super.area()*length; } public static void main(String args[]){ Cylinder cyl = new Cylinder(2.0,3.0); DecimalFormat fmt = new DecimalFormat("0.00"); System.out.println(Radius of cylinder: + cyl.getRadius()); System.out.println(Length of cylinder: + cyl.getLength()); System.out.println(Volumn of cylinder: + fmt.format(cyl.volume())); System.out.println(Area of cylinder: + fmt.format(cyl.area())); } } 2*super.area() + super.perimeter()*length ;
Kt qu ca Cylinder.java 4) Cc b t ca lp (class modifiers): Lp trong java c 3 tnh cht c trng bi 3 t kha b t sau: - public : lp c th c truy cp t cc khi khc (packages). - final : lp khng th to dn xut (lp hng) - abstract : lp tru tng.
Trang 41
http://www.ebook.edu.vn
Lp trnh Java
5) Lp tru tng i khi ta nh ngha mt lp m khng th bit v nh ngha cc thnh phn, phng thc ca n. Ta khai bo lp l mt lp tru tng. Cc thnh phn cc lp dn xut s c khai bo c th.
Shape
Cirlce
Retangle
Cylinder
Ta nh ngha lp Shape l lp tru tng, do khng th nh ngha cc thnh phn ca lp mt cch c th. C php: public abstract class <tn lp tru tng>{ ... public abstract <kiu d liu> Phng thc(); ... } V d: public abstract class Shape{ public abstract double area(); } // lp Circle dn xut t lp Shape public class Circle extends Shape{ public ... } } // lp Rectangle dn xut t lp Shape public class Rectangle extends Shape{ public double area(){ // chi tit x l tnh din tch ...
Trang 42
http://www.ebook.edu.vn
double area(){
Lp trnh Java
} } Lu : - Mt phng thc tnh (static) hay ring t (private) khng c nh ngha l tru tng, v khi c khai bo l private hay static, cc phng thc ny s khng c khai bo chng (overriding) bi cc lp dn xut. 6) Lp trong (Inner class): Lp trong, hay lp lng (nest class), l lp c nh ngha trong phm vi mt lp khc. V d: public class TestProgram{ static int currentCount; // inner class static class Apple{ private int weight; public Apple(int weight){ this.weight=weight; currentCount++; } public int getWeight(){ return weight; } } //end inner class public static void main(String args[]){ Apple a = new Apple(15); System.out.println(a.getWeight()); } }
Lp trong Apple
Trang 43
http://www.ebook.edu.vn
Lp trnh Java
Kt qu ca TestProgram.java c tnh ca lp trong l: - Lp trong c th tham chiu d liu v phng thc nh ngha ti lp (lng) ngoi. V vy ta khng cn chuyn tham chiu ca lp ngoi n phng thc to dng ca lp trong. - Lp trong c th lm cho chng trnh tr nn n gin v r rng. - Lp trong ch nhm h tr cng vic ca lp ngoi v c bin dch thnh lp OutClassNam$InnerClassName.class.
Lp trnh Java
public boolean isFull(); public boolean isEmpty(); } - Giao din IStackTwo.java public interface IStackTwo{ public void push(Object item); public Object pop(); } - Cu trc khai bo lp thc thi giao din: [modifier] class <ClassName> implements <I1>, <I2>{ // nh ngha lp } V d: Ta nh ngha lp Stack thc thi 2 giao din IStackOne v IStackTwo - Tp tin Stack.java public class Stack implements IStackOne, IStackTwo{ // khai bo d liu private Object data[]; private int top; // constructor public Stack(int size){ data = new Object[size]; top=-1; } // phng thc kim tra Stack y public boolean isFull(){ return top==data.length-1; } // phng thc kim tra Stack rng public boolean isEmpty(){ return top==-1; } //phng thc thm phn t vo Stack public void push(Object item){ if(!isFull()) data[++top]=item;
Trang 45
http://www.ebook.edu.vn
Lp trnh Java
} //phng thc ly phn t khi Stack public Object pop(){ return data[top--]; } // phng thc chnh public static void main(String args[]){ Stack s= new Stack(10); IStackOne isone =(IStackOne)s; IStackTwo istwo =(IStackTwo)s; istwo.push("C++"); istwo.push("Java"); while(!isone.isEmpty()){ System.out.println(istwo.pop()); } } }
Kt qu ca Stack.java
Lp trnh Java
System.out.println(s1 different s2) ; So snh i chiu gia 2 chui: s1.compareTo(String s2) - Phng thc tr v 0 nu s1 bng s2 - Phng thc tr v < 0 nu s1 < s2 - Phng thc tr v > 0 nu s1>< s2 Ghp hai chui: s1.concat(String s2) - Phng thc tr v chui c ghp. Trch chui con t 1 chui: s.substring( int begin, int end) - Phng thc tr v chui con bt u t ch s begin n end-1 Tr v chiu di chui. s.length() Truy xut k t ti ch s index trong chui. s.charAt(int index) Tm v tr chui s2 xut hin trong chui s1 bt u t ch s index s1.indexOf( String s2, int index): - Phng thc tr v -1 nu khng c chui s2 trong s1. - Phng thc tr v 1 nu khng c chui s2 trong s1. String s1= "Welcome to java !"; String s2= "java"; int pos = s1.indexOf(s2,0)); // gi tr ca pos l 11
Trang 47
http://www.ebook.edu.vn
Lp trnh Java
I. KHI NIM:
- Khi Java c pht hnh, cc thnh phn ha tp trung vo th vin mang tn AWT (Abstract Windows Toolkit). AWT rt hu ch trong thit k chng trnh ng dng GUI nhng khng dng thit k nhng project GUI ton din. Ngoi ra, AWT c kh nng mc li h nn. T Java 2, cc thnh phn giao din ngi dng thay th bng th vin Swing linh hot, a nng v mnh m hn.Thnh phn Swing t ph thuc h nn hn. Mc d thnh phn AWT vn c h tr trong Java 2, nhng bn nn lp trnh vi thnh Swing, bi l thnh phn AWT dn dn s li thi. - Java cung cp th vin lp rt phong ph nhm tr gip thit lp giao din ngi dng dng ha. Ta c th s dng nhiu lp thit k GUI khc nhau nh khung, panel, nt nhn, trng vn bn, vng vn bn, hp combo, chn, nt radio, menu, thanh cun,... thit k giao din ngi dng.
Lp trnh Java
- void setIconImage (Image img): gn li biu tng cho ca s. - void setVisible (boolean b): hin hoc n ca s ra mn hnh V d: package chapter04; import javax.swing.*; public class Main{ public static void main(String[] args){ JFrame frm= new JFrame("My Application"); frm.setSize(300,200); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } }
Kt qu ca MyFrame.java Thng thng khi to ca s, ta nn k tha thay cho vic s dng trc tip. V d: package chapter04; import javax.swing.*; public class MyFrame extends JFrame{ public MyFrame(String title){ super(title); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args){ MyFrame frm = new MyFrame("My Appplication"); frm.setSize(300,200); frm.setVisible(true); }
Trang 49
http://www.ebook.edu.vn
Lp trnh Java
Component Component
MouseEvent KeyEvent
2) ng k, lng nghe v x l bin c: Java s dng m hnh da trn s y nhim x l bin c. Hnh ng ca ngi dng tc ng ln i tng ngun s pht sinh bin c. i tng no quan tm n bin c s tip nhn bin c. i tng nh th gi l i tng lng nghe (listener). Mun tr thnh i tng lng nghe, i tng phi c i tng ngun ng k lm listener. i tng ngun s duy tr danh sch i tng lng nghe v thng bo n tt
Trang 50
http://www.ebook.edu.vn
Lp trnh Java
c i tng lng nghe ng k bng cch gi phng thc x l bin c (gi l handler ) trn i tng lng nghe, nhm hi p bin c. M hnh bin c:
Event Object Pht sinh i tng bin c Khi to bin c Source Object ng k i tng lng nghe
- Phng thc ng k ph thuc vo loi bin c. Thng theo c php tng qut l: addXListener (XListener) V d: - i vi bin c ActionEvent, phng thc m i tng ngun ng k l addActionListener. h thng kch hot phng thc x l (handler) trn i tng lng nghe, i tng lng nghe phi thi hnh phng thc x l chun. Phng thc x l c nh ngha trong giao din lng nghe bin c tng ng. Java cung cp giao din lng nghe cho tng loi bin c ha. Mi i tng lng nghe phi thc thi (implements) giao din tng ng. Cc loi bin c, giao din lng nghe tng ng thng dng v cc phng thc nh ngha trong giao din lng nghe.
Lp bin c ActionEvent ItemEvent TextEvent FocusEvent MouseEvent Giao din lng nghe ActionListener ItemListener TextListener FocusListener MouseListener Loi bin c pht sinh actionPerformed (ActionEvent e) itemStateChanged (ItemEvent e) textValueChanged (TextEvent e) focusGained (FocusEvent e) focusLost (FocusEvent e) mousePressed (MouseEvent e) mouseReleased (MousEvent e) mouseClicked (MouseEvent e) mouseEntered (MouseEvent e) mouseExited (MouseEvent e) mouseMoved (MouseEvent e) moouseDragged (MouseEvent e) keyPressed (KeyEvent e) keyReleased (KeyEvent e) keyTyped (KeyEvent e) adjustmentValueChanged (AdjustmentEvent e )
AdjustmentEvent
AdjustmentListener
Trang 51
http://www.ebook.edu.vn
Lp trnh Java
3) X l bin c: i tng lng nghe phi thc thi giao din lng nghe tng ng. Ly v d, i tng lng nghe dnh cho i tng ngun JButton buc phi thc thi giao din ActionListener. Giao din ActionListener cha phng thc actionPerformed (ActionEvent e). Phng thc ny phi c nh ngha li trong lp i tng lng nghe. Ngay khi c thng bo, phng thc actionPerformed (ActionEvent e) s c thi hnh hu x l bin c. V d 2: X l bin c hnh ng (ActionEvent) n gin - Chng trnh sau hin th nt Close trong ca s. Khi ngi dng click nt Close chng trnh s kt thc. package chapter04; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TestActionEvent extends JFrame{ private JButton btnClose; public TestActionEvent(){ setTitle("Test ActionEvent"); btnClose= new JButton("Close"); getContentPane().setLayout(new FlowLayout()); getContentPane().add(btnClose); // ng k i tng lng nghe btnClose.addActionListener(new MyActionListener()); } // nh ngha lp i tng lng nghe class MyActionListener implements ActionListener{ // nh ngha li phng thc hnh ng public void actionPerformed(ActionEvent e){ if(e.getSource()==btnClose) System.exit(0); } } public static void main(String args[]){ TestActionEvent frm = new TestActionEvent(); frm.setSize(300,200);
Trang 52
http://www.ebook.edu.vn
Lp trnh Java
frm.setVisible(true); } }
Kt qu ca TestActionEvent.java V d: X l bin c mouse (MouseEvent) n gin. - Chng trnh sau to khung ca s v hin th hnh trn t y ti con tr mouse khi nhp mouse. package chapter04; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TestMouseEvent extends JFrame{ private int x,y=0; // ta x,y public TestMouseEvent(){ setTitle("Test MouseEvent"); // ng k i tng lng nghe addMouseListener(new MyMouseListener()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void paint(Graphics g){ g.fillOval(x-5,y-5,10,10); } // nh ngha lp i tng lng nghe class MyMouseListener implements MouseListener{ // nh ngha li phng thc nhp mouse public void mousePressed(MouseEvent e){ x=e.getX();
Trang 53
http://www.ebook.edu.vn
// v hnh oval
Lp trnh Java
y=e.getY(); repaint(); } public void mouseReleased(MouseEvent e){ } public void mouseClicked(MouseEvent e){ } public void mouseEntered(MouseEvent e){ } public void mouseExited(MouseEvent e){ } } public static void main(String args[]){ TestMouseEvent frm = new TestMouseEvent(); frm.setSize(300,200); frm.setVisible(true); } } // gi li phng thc paint()
Kt qu ca TestMouseEvent.java Lu : - Qun khng ng k i tng lng nghe l li thng gp trong x l bin c. Nu h thng khng khai bo i tng lng nghe, i tng lng nghe khng th hot ng trn bin c. 4) Lp iu hp v lp khng tn: - M hnh bin c Java rt linh hot, n cho php hiu chnh v chp nhn bin th. Mt trong nhng bin th hu ch ca m hnh l lp iu hp (adapter) x l bin c. Lp iu hp c ng k di dng i tng lng nghe cho i tng ngun. Java cung cp lp iu hp tin dng cho tng giao din lng nghe bin c vi nhiu phng thc x l. Lp iu hp ch l mt thc thi n gin ca giao din lng nghe bin c, cha cc phng thc rng cho tng phng thc nh ngha trong giao din. - Ch c nhng giao din lng nghe cha t 2 phng thc tr ln th mi c lp iu hp. Thng thng mt giao din lng nghe XListener th s c mt XAdapter.
Trang 54
http://www.ebook.edu.vn
Lp trnh Java
V d: MouseListener th s c MouseAdapter. Lp i tng lng nghe c th m rng (extends) lp iu hp x l bin c thay v thc thi (implements) giao din lng nghe. V d: - Ta c th s dng lp iu hp thay v giao din lng nghe trong chng trnh x l bin c mouse n gin.
package chapter04; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TestMouseEventUsingAdapter extends JFrame{ private int x,y=0; // ta x,y public TestMouseEventUsingAdapter(){ setTitle("Test MouseEvent"); // ng k i tng lng nghe addMouseListener(new MyMouseListener()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void paint(Graphics g){ g.fillOval(x-5,y-5,10,10); } // nh ngha lp i tng lng nghe class MyMouseListener extends MouseAdapter{ // nh ngha li phng thc nhp mouse public void mousePressed(MouseEvent e){ x=e.getX(); y=e.getY(); repaint(); } } public static void main(String args[]){ TestMouseEventUsingAdapter frm = new TestMouseEventUsingAdapter(); frm.setSize(300,200); frm.setVisible(true); } } Trang 55
http://www.ebook.edu.vn
// v hnh oval
Lp trnh Java
- Chng trnh c th rt gn hn na khi dng lp trong khng tn. Lp trong khng tn (anonymouse inner class) l lp lng trong khng c tn gi. V d:
package chapter04; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TestMouseEventUsingAnonymousInnerClass extends JFrame{ private int x,y=0; // ta x,y public TestMouseEventUsingAnonymousInnerClass(){ setTitle("Test MouseEvent"); // ng k lp iu hp lm listener addMouseListener(new MouseAdapter(){ // nh ngha li phng thc nhp mouse public void mousePressed(MouseEvent e){ processMousePressed(e); } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void paint(Graphics g){ g.fillOval(x-5,y-5,10,10); } public void processMousePressed(MouseEvent e){ x=e.getX(); y=e.getY(); repaint(); } public static void main(String args[]){ TestMouseEventUsingAnonymousInnerClass frm = new TestMouseEventUsingAnonymousInnerClass(); frm.setSize(300,200); frm.setVisible(true); } } // gi li phng thc paint() // v hnh oval
Trang 56
http://www.ebook.edu.vn
Lp trnh Java
thm thnh phn vo vng cha, s dng phng thc: void add(Component p) void add(Component p,int index) V d: - Thm nt btnClose vo vng cha container: container.add(btnClose); 2) B cc FlowLayout: - Dng sp xp cc thnh phn t tri qua phi theo mt trt t nh chng thm vo. - C th canh l da vo 3 hng: FlowLayout.RIGHT FlowLayout.CENTER FlowLayout.LEFT. Phng thc khi to: public public FLowLayout(int align, int hgap, int vgap) FLowLayout(int align)
Trang 57
http://www.ebook.edu.vn
Lp trnh Java
- To FlowLayout vi kiu canh l c th, khong trng ngang v dc mc nh l 5 pixel. public FLowLayout() - To lp FlowLayout vi kiu canh l gia mc nh, khong trng ngang v dc mc nh l 5 pixel. V d: package chapter04; import java.awt.*; import javax.swing.*; public class ShowFlowLayout extends JFrame{ JButton b1,b2,b3,b4; public ShowFlowLayout(){ setTitle("Demo FlowLayout"); Container container = getContentPane(); container.setLayout(new FlowLayout(FlowLayout.LEFT)); container.add(b1= new JButton("Button 1")); container.add(b2= new JButton("Button 2")); container.add(b3= new JButton("Button 3")); container.add(b4= new JButton("Button 4")); } public static void main(String[] args){ ShowFlowLayout frm = new ShowFlowLayout(); frm.setSize(300,200); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.show(); } }
Kt qu ca ShowFlowLayout.java
Trang 58
http://www.ebook.edu.vn
Lp trnh Java
3) B cc GridLayout: - Sp xp cc thnh phn theo khung li k (ma trn) vi s dng v ct do phng thc to dng quyt nh. - Thnh phn c t vo li t tri sang phi, bt u t hng u tin, tip n l hng th hai, ... Phng thc khi to: public GridLayout(int rows,int columns,int hgap,int vgap) - To GridLayout vi s dng, ct, cng khong trng ngang v dc nh r. public GridLayout(int rows,int columns) - To GridLayout vi s dng, ct nh r, khong trng ngang v dc mc nh l 0 pixel. V d: package chapter04; import java.awt.*; import javax.swing.*; public class ShowGridLayout extends JFrame{ JButton btn[]; public ShowGridLayout(){ setTitle("Demo GridLayout"); Container container = getContentPane(); container.setLayout(new GridLayout(4,3,5,5)); btn = new JButton[10]; for(int i=0;i<btn.length;i++){ btn[i]= new JButton("Button " +(i+1)); container.add(btn[i]); } } public static void main(String[] args){ ShowGridLayout frm = new ShowGridLayout(); frm.pack(); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.show(); } }
Trang 59
http://www.ebook.edu.vn
Lp trnh Java
Kt qu ca ShowGridLayout.java 4) B cc BorderLayout: - Lp qun l BorderLayout phn chia vng cha thnh 5 khu vc (North, South,West, East, Center). - Mi khu vc c nh ngha bi 1 hng s sau: BorderLayout.NORTH BorderLayout.SOUTH BorderLayout.WEST BorderLayout.EAST BorderLayout.CENTER Phng thc khi to: public BorderLayout(int hgap, int vgap) - To BorderLayout vi khong trng ngang v dc nh r xen gia cc thnh phn. public BorderLayout() - To BorderLayout khng c khong trng ngang v dc. V d:
package chapter04; import java.awt.*; import javax.swing.*; public class ShowBorderLayout extends JFrame{ public ShowBorderLayout(){ setTitle("Demo GridLayout"); Container container = getContentPane(); container.setLayout(new BorderLayout(5,5)); container.add(new JButton("North"),BorderLayout.NORTH); container.add(new JButton("South"),BorderLayout.SOUTH); container.add(new JButton("West"),BorderLayout.WEST); container.add(new JButton("East"),BorderLayout.EAST); container.add(new JButton("Center"),BorderLayout.CENTER); }
Trang 60
http://www.ebook.edu.vn
Kt qu ca ShowBorderLayout.java Lu : - Lun lun n nh kiu trnh by tht r rng cho vng cha, mc d lp qun l BorderLayout c p dng theo mc nh cho khung ni dung ca JFrame
Lp trnh Java import javax.swing.*; public class TestPanel extends JFrame{ private JTextField txtDisplay; private JButton btnNum[]; public TestPanel(){ setTitle("TestPanels"); Container c= getContentPane(); c.setLayout(new BorderLayout()); txtDisplay =new JTextField();
// to panel ghp cc nt s bng b cc GridLayout JPanel p = new JPanel(); p.setLayout(new GridLayout(3,3)); btnNum = new JButton[10]; for(int i=0;i<btnNum.length;i++){ p.add(btnNum[i]= new JButton(String.valueOf(i))); btnNum[i].addActionListener(new MyActionListener()); } // t panel vo gia khung c.add(p,BorderLayout.CENTER); // t trng vn bn bn trn panel c.add(txtDisplay,BorderLayout.NORTH); } class MyActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ String actionCommand = e.getActionCommand(); if(e.getSource() instanceof JButton) txtDisplay.setText(actionCommand); } } public static void main(String args[]){ TestPanel frm frm.pack(); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } } Trang 62
http://www.ebook.edu.vn
= new TestPanel();
Lp trnh Java
Kt xut ca TestPanel.java 2) S dng Panel v i tng ha: - Panel thng c dng lm vt cha nh ghp nhm cc thnh phn hu thu c b cc mong mun. Cng dng quan trng khc ca JPanel l v i tng ha. - Mun v trn panel, ta cn to lp mi m rng lp JPanel v nh ngha li phng thc paintComponent () hu ch th cho panel cch v i tng ha. Mc d c php v thng ip, hnh dng v hin th hnh nh trc tip ln khung (JFrame) nhng ta vn nn dng JPanel v theo cch ny, bc v s khng nh hng n cc thnh phn khc. V d: V trn panel - Chng trnh to mt lp con ca JPanel s hin th thng ip. Ta dng mouse di chuyn thng ip v thng ip lun xut hin ti thi im t mouse. package chapter04; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PanelDrawingDemo extends JFrame{ public PanelDrawingDemo(){ setTitle("Panel Drawing Demo"); PaintPanel p =new PaintPanel("Welcome to java"); getContentPane().setLayout(new BorderLayout()); getContentPane().add(p,BorderLayout.CENTER); } public static void main(String args[]){ PanelDrawingDemo frm = new PanelDrawingDemo(); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setSize(300,200); frm.setVisible(true); } }
Trang 63
Lp trnh Java
// class PaintPanel draw a message class PaintPanel extends JPanel{ private String message; private int x,y; public PaintPanel(String msg){ message=msg; this.addMouseMotionListener(new MouseMotionAdapter(){ public void mouseMoved(MouseEvent e){ x=e.getX(); y=e.getY(); repaint(); } }); } public void paintComponent(Graphics g){ super.paintComponent(g); //clear the viewing area g.drawString(message,x,y); } }
Kt xut ca PanelDrawingDemo.java
Lp trnh Java
- To nt vi biu tng ch nh. public JButton(String text, Icon icon) - To nt vi nhn v biu tng ch nh Mt s phng thc thng dng trn Jbuton: void setText(String text) - t li nhn cho nt void setIcon(Icon icon) - t li biu tng cho nt void setEnabled( boolean b) - t tnh hiu lc cho nt void setToolTipText(String text) - t ch thch (tooltiptext) cho nt void setMnemonic(char c) - nh phm tt void setVisible(boolean b) - Cho nt n hoc hin V d: - Chng trnh sau hin th mt chui trong trng vn bn, click 2 nt left, right canh l tri, l phi v click nt close kt thc chng trnh.
package chapter04; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ButtonDemo extends JFrame{ private JButton btnLeft,btnRight,btnClose; private JTextField txtdisplay; public ButtonDemo(){ setTitle("Button Demo"); Container c = getContentPane(); JPanel p = new JPanel(); p.setLayout(new FlowLayout()); p.add(btnLeft= new JButton("Left")); p.add(btnRight= new JButton("right")); Icon icon = new ImageIcon(this.getClass().getResource( "images/close.jpg")); p.add(btnClose= new JButton("Close",icon)); c.add(p,BorderLayout.CENTER); Trang 65
Lp trnh Java
c.add(txtdisplay=new JTextField("Welcome to java",20) ,BorderLayout.NORTH); MyActionListener myAction = new MyActionListener(); btnLeft.addActionListener(myAction); btnRight.addActionListener(myAction); btnClose.addActionListener(myAction); } class MyActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ if(e.getSource()==btnLeft){ txtdisplay.setHorizontalAlignment(JTextField.LEFT); }else if(e.getSource()==btnRight){ txtdisplay.setHorizontalAlignment(JTextField.RIGHT); }else if(e.getSource()==btnClose){ System.exit(0); } } } public static void main(String[] args){ ButtonDemo frm = new ButtonDemo(); frm.pack(); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } }
Kt qu ca ButtonDemo.java 2) JLabel (nhn): L vng hin th mt chui k t ngn, hnh nh hoc c hai. Phng thc to dng: public JLabel(String text) - To nhn vi chui k t cho trc. public JLabel(String text, int align)
Trang 66
Lp trnh Java
- To nhn vi chui k t cho trc v c canh l. public JLabel(Icon icon) - To nhn vi biu tng. Phng thc phng thc thng dng trn JLabel void setText(String text) - t li nhn void setIcon(Icon icon) - t li icon cho nhn Cc hng s canh l: - JLable.RIGHT - JLable.LEFT - JLable.CENTER. 3) JTextField (trng vn bn): Thnh phn cho php nhp mt dng vn bn Phng thc to dng: public JTextField(int columns) - To trng vn bn trng vi s ct ch nh public JTextField(String text) - To trng vn bn vi chui nh r public JTextField(String text, int columns) - To trng vn bn vi ni dung cho trc v s ct ch nh Mt s phng thc thng dng trn JTextField void setText(String text) - t li ni dung cho trng vn bn String getText() - Ly v ni dung trong vng vn bn void setEditable(boolean state - Cho php ngi dng c th hiu chnh hay khng V d: - Chng trnh mu nhp hai tr s vo hai trng vn bn v hin th tng ca chng trng th 3 khi nhp nt Add.
package chapter04; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class TextFieldDemo extends JFrame{ Trang 67
private JTextField txtNum1,txtNum2,txtResult; public TextFieldDemo(){ setTitle("Button Demo"); Container c = getContentPane(); JPanel p1 = new JPanel(); p1.setLayout(new FlowLayout()); p1.add(new JLabel("Number 1")); p1.add(txtNum1 = new JTextField(3)); p1.add(new JLabel("Number 2")); p1.add(txtNum2 = new JTextField(3)); p1.add(new JLabel("Result")); p1.add(txtResult = new JTextField(4)); txtResult.setEditable(false); JPanel p2= new JPanel(); p2.setLayout(new FlowLayout()); p2.add(btnAdd= new JButton("Add")); c.add(p1,BorderLayout.CENTER); c.add(p2,BorderLayout.SOUTH); MyActionListener myAction = new MyActionListener(); btnAdd.addActionListener(myAction); } class MyActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ if(e.getSource()==btnAdd){ double num1 = Double.parseDouble(txtNum1.getText()); double num2 = Double.parseDouble(txtNum2.getText()); double result = num1 + num2; txtResult.setText(String.valueOf(result)); } } } public static void main(String[] args){ TextFieldDemo frm= new TextFieldDemo(); frm.pack(); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } Trang 68
Lp trnh Java }
Kt qu ca TextFieldDemo.java 4) JTextArea (Vng vn bn): Thnh phn cho php ngi dng g nhiu dng vn bn. Phng thc to dng: public JTextArea(int rows, int cols) - To vng vn bn vi s dng, ct xc nh. public JTextArea(String text, int rows, int cols) - To vng vn bn vi s dng, ct ch nh v ni dung cho trc Mt s phng thc thng dng trn JTextArea void setText(String text) - t li ni dung String getText() - Ly v ni dung void setEditable(boolean b) - Cho php ngi dng c th chnh sa vn bn hay khng. void setLineWrap(boolean b) - Cho bit dng ch c t ng xung dng khng. String getSelectedText() - Ly v ni dung vn bn c nh du chn void append(String s) - Thm chui s vo cui vn bn void insert(String s,int pos) - Chn chui s vo v tr nh trong vng vn bn. void replaceRange(String s, int start, int end) - Thay th phn vn bn t v tr start n v tr end bng chui s. Lu : - Lp JTextArea khng x l thao tc cun, x l thao tc cun cho JTextArea ta c th to i tng JScrollPane cha phin bn ca lp JTextArea nh sau: JTextArea area = new JTextArea(10,30); JScrollPane scrollPane = new JScrollPane(area);
Trang 69
Lp trnh Java
getContentPane().add(scrollPane, BorderLayout, CENTER); V d: - Chng trnh mu cho php ngi dng nhp vn bn t trng vn bn, sau ghi ni vo cui ni dung vng vn bn.
package chapter04; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TextAreaDemo extends JFrame{ private JTextArea area; private JButton btnStore; private JTextField txtInput; public TextAreaDemo(){ setTitle("Test TextArea"); JPanel p =new JPanel(); p.setLayout(new FlowLayout()); p.add(new JLabel("Input")); p.add(txtInput= new JTextField(20)); p.add(btnStore= new JButton("Store")); // create a scroll pane to hold text area JScrollPane scrollPane = new JScrollPane(area = new JTextArea(5,20)); area.setLineWrap(true); getContentPane().add(scrollPane,BorderLayout.CENTER); getContentPane().add(p,BorderLayout.SOUTH); // register listener MyActionListener myAction = new MyActionListener(); txtInput.addActionListener(myAction); btnStore.addActionListener(myAction); } class MyActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ area.append(txtInput.getText().trim()); } } public static void main(String args[]){ TextAreaDemo frm = new TextAreaDemo(); Trang 70
Lp trnh Java
Kt qut ca TextAreaDemo.java 5) JComboBox (Hp combo) L danh sch lit k nhng khon mc m ngi dng c th chn la. Phng thc to dng: public JComboBox() - To danh sch rng Mt s phng thc thng dng trn JcomboBox: void addItem(Object item) - Thm mt i tng vo hp combo Object getItemAt(int index) - Ly v khon mc t hp combo ti ch s nh. Object getSelectedItem() - Ly v khon mc c chn trn combo bi ngi dng. void removeItem( Object item) - Xo mt khon mc khi danh sch. void removeAllItems() - Xo ton b cc khon mc khi danh sch. int getItemCount() - Tr v s khon mc ca danh sch. 6) JList (danh sch): L thnh phn, v c bn, c cng chc nng vi hp combo, nhng n cho php ngi dng chn gi tr n l hoc nhiu gi tr. Phng thc to dng: public JList(Object []) - To danh sch vi mng khon mc ch nh.
Trang 71
Lp trnh Java
Mt s phng thc thng dng trn Jlist: int getSelectedIndex() - Tr v ch s ca khon mc c chn trong danh sch. int[] getSelectedIndices() - Tr v mng gi tr biu th ch s cc khon mc c chn. Object getSelectedValue() - Tr v gi tr c chn u tin trong danh sch. Object[] getSelectedValues() - Tr v mng i tng biu th cc gi tr c chn. void setSelectionMode(int mode) - t ch chn cho danh sch. Lu : - Danh sch khng t ng cun. danh sch cun c, ta dng khung cun (scroll pane) v t danh sch vo y, tng t nh JTextArea. - Danh sch JList pht sinh bin c javax.swing.event.ListSelectionEvent thng bo n cc i tng lng nghe v khon mc c chn. i tng lng nghe phi thc thi phng thc valueChanged () hu x l bin c. V d: - Chng trnh sau cho php ngi dng chn tn sch trong danh sch v hin th nh ba ca sch trong nhn.
package chapter04; import javax.swing.*; import java.awt.*; import javax.swing.event.*; public class ListDemo extends JFrame{ private JList lstBook; private JLabel lbBookImage; private ImageIcon bookImage[]= new ImageIcon[5]; public ListDemo(){ setTitle("List Demo"); String bookName[]={"Java 2 Programming", "Java Networking", "Java with OOP", Jsp/Servlet Web Programing", Java 2 Research}; JScrollPane scrollPane = new JScrollPane( lstBook = new JList(bookName)); Trang 72
Lp trnh Java
getContentPane().add(scrollPane,BorderLayout.WEST); for(int i=0;i<bookImage.length;i++){ bookImage[i] = new ImageIcon(this.getClass().getResource( "images/" + i + ".jpg")); } lbBookImage = new JLabel(bookImage[0]); getContentPane().add(lbBookImage,BorderLayout.CENTER); // register listeners lstBook.addListSelectionListener(new MySelectionListener()); } class MySelectionListener implements ListSelectionListener{ public void valueChanged(ListSelectionEvent e){ lbBookImage.setIcon(bookImage[ lstBook.getSelectedIndex()]); } } public static void main(String args[]){ ListDemo frm = new ListDemo(); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.pack(); frm.setVisible(true); } }
Kt qu ca ListDemo.java 7) JCheckBox v JradioButton: a) JCheckBox ( chn): - Thnh phn cho php ngi dng chn hoc xa chn mt ty chn. - Hnh dng: Phng thc to dng: public JCheckBox(String text)
Trang 73
Lp trnh Java
- To chn vi chui vn bn ch nh. public JCheckBox(String text, boolean selected) - To chn vi chui vn bn ch nh v nh r trng thi ban u ca chn. Mt s phng thc thng dng trn JcheckBox: void setText(String text) - t li nhn cho chn void setIcon( Icon icon) - t li biu tng cho chn void setVisible(boolean b) - Cho chn n hoc hin public boolean isSelected() - Tr v trng thi chn b) JRadioButton (nt radio) - L thnh phn tng t nh JcheckBox. - Hnh dng: Phng thc to dng: public JRadioButton(String) public JRadioButton(String, boolean) - Mun nhm cc nt radio li vi nhau, ta cn to i tng javax.swing.ButtonGroup v t nt radio vo i tng bng phng thc add (), chng hn nh on m minh ha sau: JRadioButton jrd1 = new JRadioButton(Male,true); JRadioButton jrd2 = new JRadioButton(Female); ButtonGroup btg= new ButtonGroup(); btg.add(jrb1); btg.add(jrb1); V d: - Chng trnh mu cho php nh dng chui k t trong vng vn bn, ngi dng c th chn in m v in nghing cng lc. Cng c th chn mu ch cho vng vn bn.
package chapter04; import java.awt.*; import javax.swing.*; import javax.swing.border.*; import java.awt.event.*; public class BorderDemo extends JFrame{ Trang 74
Lp trnh Java private JCheckBox chkBold,chkItalic; private JRadioButton jrdBlue, jrdBlack; private JTextArea area; public BorderDemo(){ setTitle("BorderDemo"); Container c = getContentPane(); JPanel p1 = new JPanel(); p1.setLayout(new FlowLayout()); // set TitledBorder for panel p1
p1.setBorder(new TitledBorder(new EtchedBorder(), "Font style")); p1.add(chkBold= new JCheckBox("Bold")); p1.add(chkItalic= new JCheckBox("Italic")); JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(2,1)); // set TitledBorder to panel p2 p2.setBorder(new TitledBorder(new EtchedBorder(), "Font color")); p2.add(jrdBlue= new JRadioButton("Green")); p2.add(jrdBlack= new JRadioButton("White")); ButtonGroup btg =new ButtonGroup(); btg.add(jrdBlue); btg.add(jrdBlack); c.add(p1,BorderLayout.SOUTH); c.add(p2,BorderLayout.EAST); JScrollPane scrollPane = new JScrollPane(area = new JTextArea("Welcome to java")); c.add(scrollPane,BorderLayout.CENTER); // register listener MyItemListener myAction = new MyItemListener(); chkBold.addItemListener(myAction); chkItalic.addItemListener(myAction); jrdBlue.addItemListener(myAction); jrdBlack.addItemListener(myAction); } class MyItemListener implements ItemListener{ public void itemStateChanged(ItemEvent e){ int selectedStyle=0; Trang 75
selectedStyle = selectedStyle + Font.BOLD; if(chkItalic.isSelected()) selectedStyle = selectedStyle + Font.ITALIC; area.setFont(new Font("Monospaced",selectedStyle,12)); if(jrdBlue.isSelected()) area.setForeground(Color.blue); else area.setForeground(Color.BLACK); } } public static void main(String[] args){ BorderDemo frm= new BorderDemo(); frm.setSize(300,200); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } }
Kt qu ca JCheckBoxRadioButtonDemo.java Border (khung vin): - L mt trong nhng c tnh mi th v ca thnh phn swing (c cha trong gi javax.swing.border). - Ta thng thit lp khung vin c tiu trn lp JPanel, ghp nhm tp hp thnh phn giao din ngi dng c lin quan nhau. - t khung vin c tiu cho panel, ta thng dng lnh sau:
JPanel p = new JPanel(); p.setBorder(new TitledBorder(new EtchedBorder(),"Tiu "));
Trang 76
Lp trnh Java
8) JOptionPane (Hp thoi thng bo): - Thng c dng lm ca s tm nhn thm thng tin t ngi dng, hoc thng bo v nhng bin c xy ra Cc thnh phn ca ca s dng hp thoi thng bo l:
Biu tng
Thng ip Nt ty chn
C php: public showMessageDialog(Component ParentComponent, Object Message, String Title, int MessageType) - ParentComponet: l thnh phn cha ca hp thoi, ni hp thoi khi ng. - Message: l i tng cn hin th - Title: l tiu hp thoi - Messagetype: l kiu thng ip hin th. C 5 kiu thng ip: ERROR_MESSAGE INFORMATION_MESSAGE PLAIN_MESSAGE WARNING_MESSAGE QUESTION_MESSAGE V d: - Cu lnh sau hin th mt thng ip Welcome to java. JOptionPane.showMessageDialog(null, "Welcome to java", "Welcome", JOptionPane.INFORMATION_MESSAGE);
Trang 77
Lp trnh Java
9) Menu (thc n): Menu gip chn la d dng v c s dng rng ri trong cc chng trnh ng dng dng ca s. Java cung cp 5 lp: JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem v JRadioButtonMenuItem s dng to menu.
JMenu JMenuItem
JMenuBar JRadionButtonMenuItem
JCheckBoxMenuItem
Trnh t ng dng menu trong java: - To thanh menu v phi hp n vi khung bt k: JFrame frm = new JFrame("Menu Demo"); JMenuBar jmb = new JMenuBar(); frm.setJMenuBar(jmb); - To menu: S dng phng thc to dng sau y: public V d: JMenu JMenu fileMenu = new JMenu("File"); helpMenu = new JMenu("Help"); JMenu(String label)
jmb.add(fileMenu); jmb.add(helpMenu);
Lp trnh Java
fileMenu.addSeparator(); // To khong cch trong menu fileMenu.add(new JMenuItem("Print")); fileMenu.addSeparator(); // To khong cch trong menu fileMenu.add(new JMenuItem("Exit")); on m ny ln lt b sung cc khon mc New, Open, vch phn cch, Print, vch phn cch v Exit vo menu File.
To cc khon mc trn menu con. - Ta cng c th nhng menu bn trong menu, lc menu c nhng tr thnh menu con. JMenu softwareHelpSubMenu = new JMenu("Software"); helpMenu.add(softwareHelpSubMenu); helpMenu.add(new JMenuItem("About")); softwareHelpSubMenu.add(new JMenuItem("Unix")); softwareHelpSubMenu.add(new JMenuItem("Win2003")); softwareHelpSubMenu.add(new JMenuItem("Linux")); on m ny thm menu softwareHelpSubMenu v khon mc About vo trong helpMenu. Cc khon mc Unix, Win2003 v Linux vo menu softwareHelpSubMenu.
Trang 79
Lp trnh Java
10)Biu tng nh, phm tt quy c v phm tng tc. Cc thnh phn JMenu, JMenuItem, JCheckBoxMenuItem, JRadioButtonMenuItem u c phng thc setIcon (Icon icon) v setMnemonic (char c) t biu tng v phm tt quy c cn thit. V d: JMenuItem jmiNew,jmiOpen; fileMenu.add(jmiNew=new JMenuItem("New")); fileMenu.add(jmiOpen=new JMenuItem("Open")); // t biu tng cho khon mc New v Open jmiNew.setIcon(new ImageIcon(getClass().getResource("images/new.gif"))); jmiOpen.setIcon(new ImageIcon(getClass().getResource("images/open.gif"))); // t phm tt qui c cho menu File v Help fileMenu.setMnemonic('F'); helpMenu.setMnemonic('H');
- Mun chn menu, nhn ALT v phm tt quy uc. Chng hn, t hp ALT+ F s chn menu File. Ngoi ra ta c th dng phm tng tc cho php chn trc tip khon mc bng cch nhn phm Ctrl v phm tng tc. V d: - To t hp phm Ctrl O thc hin khon mc Open. jmiOpen.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_O,ActionEvent.CTRL_MASK)); - Phng thc setAccelerator () a ra i tng KeyStroke. - Phng thc lp getKeyStroke () ca lp KeyStroke to phin bn ca c g phm. VK_O l hng biu th phm O, CTRL_MASK l hng cho bit phm Ctrl c phi hp vi phm g.
Trang 80
Lp trnh Java
V d: - Chng trnh mu to giao din ngi dng thc hin cc php ton s hc. Giao din cha nhn v trng vn bn cho Number 1, Number 2 v Result. - Trng Result hin th kt qu ca php ton s hc gia Number 1 v Number 2. - Chng trnh c 4 nt Add, Subtract, Multiply, Divide - Ngoi ra cn to menu thc hin cng php ton. Ngi dng c th chn php ton t nt hoc t menu.
package chapter04; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.text.DecimalFormat; public class MenuDemo extends JFrame{ private JButton btnAdd,btnSub,btnMul, btnDiv; private JTextField txtNum1,txtNum2,txtResult; private JMenuItem jmiAdd, jmiSub, jmiMul,jmiDiv, jmiClose; private DecimalFormat fmt = new DecimalFormat("0.00"); public MenuDemo(){ setTitle("Menu Demo"); // create menu bar JMenuBar jmb= new JMenuBar(); // set menu bar to the frame setJMenuBar(jmb); //add menu "Operation" to menu bar JMenu operMenu = new JMenu("Operation"); operMenu.setMnemonic('O'); jmb.add(operMenu); //add menu items with mnemonics to menu "Operation" operMenu.add(jmiAdd= new JMenuItem("Add",'A')); operMenu.add(jmiSub= new JMenuItem("Subtract",'S')); operMenu.add(jmiMul= new JMenuItem("Multiply",'M')); operMenu.add(jmiDiv= new JMenuItem("Divide",'D')); operMenu.addSeparator(); operMenu.add(jmiClose= new JMenuItem("Close")); //set keyboard accelerators jmiAdd.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_A,ActionEvent.CTRL_MASK)); jmiSub.setAccelerator(KeyStroke.getKeyStroke( Trang 81
Lp trnh Java
jmiMul.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_M,ActionEvent.CTRL_MASK)); jmiDiv.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_D,ActionEvent.CTRL_MASK)); Container c = getContentPane(); JPanel p1 = new JPanel(); p1.setLayout(new FlowLayout()); p1.add(new JLabel("Number 1")); p1.add(txtNum1 = new JTextField(3)); p1.add(new JLabel("Number 2")); p1.add(txtNum2 = new JTextField(3)); p1.add(new JLabel("Result")); p1.add(txtResult = new JTextField(4)); txtResult.setEditable(false); JPanel p2= new JPanel(); p2.setLayout(new FlowLayout()); p2.add(btnAdd= new JButton("Add")); p2.add(btnSub= new JButton("Subtract")); p2.add(btnMul= new JButton("Multiply")); p2.add(btnDiv= new JButton("Divide")); c.add(p1,BorderLayout.CENTER); c.add(p2,BorderLayout.SOUTH); //register listener MyActionListener myAction = new MyActionListener(); btnAdd.addActionListener(myAction); btnSub.addActionListener(myAction); btnMul.addActionListener(myAction); btnDiv.addActionListener(myAction); jmiAdd.addActionListener(myAction); jmiSub.addActionListener(myAction); jmiMul.addActionListener(myAction); jmiDiv.addActionListener(myAction); jmiClose.addActionListener(myAction); } class MyActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ String actionCommand = e.getActionCommand(); Trang 82
else if(actionCommand.equals("Subtract")) calculator('-'); else if(actionCommand.equals("Multiply")) calculator('*'); else if(actionCommand.equals("Divide")) calculator('/'); } else if(e.getSource() instanceof JMenuItem){ if(actionCommand.equals("Add")) calculator('+'); else if(actionCommand.equals("Subtract")) calculator('-'); else if(actionCommand.equals("Multiply")) calculator('*'); else if(actionCommand.equals("Divide")) calculator('/'); else if(actionCommand.equals("Close")) System.exit(0); } } } private void calculator(char operator){ double num1 = Double.parseDouble(txtNum1.getText()); double num2 = Double.parseDouble(txtNum2.getText()); double result = 0; switch(operator){ case '+': result=num1+num2; break; case '-': result=num1-num2; break; case '*': result=num1*num2; break; case '/': result=num1/num2; break; } Trang 83
Lp trnh Java txtResult.setText(fmt.format(result)); } public static void main(String[] args){ MenuDemo frm = new MenuDemo(); frm.pack();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } }
Kt xut ca MenuDemo.java 11)JTabbedPane (Khung nhiu tab): - L thnh phn Swing hu ch, cung cp tp hp tab loi tr nhau truy cp nhiu thnh phn. - Ta thng t panel bn trong mt JTabbedPane v phi hp tab vi mi panel. JTabbedPanel rt d s dng, v panel t ng c chn bng cch nhp tab tng ng. Phng thc khi to: public JTabbedPane() - To khung trng c nhiu tab. Mun b sung thnh phn vo JTabbedPane, s dng phng thc: public add(Component component, Object constraints) - Component l thnh phn hin th khi tab c nhp - Contraints c th l tiu ca tab. V d: - Chng trnh dng nhiu khung tab vi 2 tab hin th 2 dng hnh Square (hnh vung), Circle (hnh trn). - Chn hnh cn hin th bng cch nhp tab tng ng.
package chapter04; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TabbedPaneDemo extends JFrame{ Trang 84
Lp trnh Java
private JTabbedPane jtpFigure = new JTabbedPane(); public TabbedPaneDemo(){ setTitle("TabbedPane Demo"); // add FigurePanel to the tab jtpFigure.add(new FigurePanel( FigurePanel.SQUARE),"Square"); jtpFigure.add(new FigurePanel( FigurePanel.CIRCLE),"Circle"); getContentPane().add(jtpFigure); } class FigurePanel extends JPanel{ final static int SQUARE =1; final static int CIRCLE =2; private int figure=1; public FigurePanel(int fig){ figure =fig; this.setBackground(Color.white); } //drawing a figure on the panel public void paintComponent(Graphics g){ super.paintComponent(g); int width= getSize().width; int height= getSize().height; int side =(int)(0.5*Math.min(width,height)); switch(figure){ case 1: g.drawRect((width-side)/2, (height-side)/2,side,side); break; case 2: g.drawOval((width-side)/2, (height-side)/2,side,side); break; } } } //end inner class public static void main(String args[]){ TabbedPaneDemo frm = new TabbedPaneDemo(); frm.setSize(300,200); frm.setVisible(true); Trang 85
Lp trnh Java } }
Kt xut ca TabbedPaneDemo.java
Trang 86
Lp trnh Java
X l bit l
Chng 5 X L BIT L
Sau bi hc ny, hc vin c th: - Hiu c bit l v xc nh c cc dng bit l trong lp trnh java. - C kh nng phn tch v x l cc ngoi l. - Hiu c cc phng php x l ngoi l.
I. KHI NIM:
- Bit l (Exception) l li xy ra trong thi gian thc thi chng trnh (runtime error), lm gin on mch iu khin bnh thng. Thng thng cc iu kin thc thi chng trnh gy ra bit l. Nu cc iu kin ny khng c quan tm, th vic thc thi c th kt thc t ngt. - Java cung cp kh nng x l li thi hnh cho cc lp trnh vin. Vi kh nng ny, gi l kh nng x l bit l, ta c th thit k chng trnh n nh v tin cy hn khi thi hnh. Gim thiu vic kt thc bt thng ca h thng v ca chng trnh.
III. X L BIT L:
x l bit l, ta c th s dng 2 phng php: - Bt bit l. - Nm bit l.
Trang 87
Lp trnh Java
X l bit l
1) Bt bit l: C php: try{ // Cc lnh c kh nng xy ra bit dch } catch(ExceptionType1 param1){ // on lnh x l tng ng vi bit l xy ra } catch(ExceptionType2 param2){ // on lnh x l tng ng vi bit l xy ra } ... catch(ExceptionTypeN paramN){ // Exception Block } finally{ // on lnh lun thc hin bt k bit l c xy ra hay khng. } Cch thc hin ca khi try-catch: - Nu khng c bit l no xy ra trong sut qu trnh thc thi mnh try, cc mnh catch s c b qua. - Trng hp mt trong cc cu lnh bn trong khi try nm ra mt bit l, Java s b qua cc cu lnh cn li v bt u tm kim phng thc x l bit l . Nu kiu bit l so khp vi bit l lit k trong mnh catch, m trong mnh catch s c thc thi. Nu khng tm thy phng thc x l, chng trnh s chm dt v in ra thng ip bo li trn console. Khi finally: - L ty chn khng bt buc - c t sau khi catch. - Khi finally bo m lc no cng c thc hin bt chp bit l c xy ra hay khng. S hot ng:
try block No Exception finally block Exception occurs catch block
finally block
Trang 88
Lp trnh Java
X l bit l
V d: - Chng trnh sau thc hin php ton chia x cho y. Bit l s xy ra khi y=0. Chng trnh khng quan tm ti bit l. public class TestException{ public static void main(String args[]){ int x=5,y=0; int } } z=x/y; System.out.println(z= + z);
Kt qu ca TestException. Java - Chng trnh sau thc hin php ton chia x cho y. Bit l s xy ra khi y=0. Chng trnh c quan tm ti bit l v bt ngoi l nu n xy ra. public class TestException{ public static void main(String args[]){ int x=5,y=0; try{ int } catch(Exception ex){ System.out.println("Error:"+ ex.toString()); } } } z=x/y; System.out.println("z=" + z);
Trang 89
Lp trnh Java
X l bit l
V d: class ThrowsDemo{ public static void main(String args[]){ a(); } public static void a(){ try{ b(); } catch(ClassNotFoundException e){ e.printStackTrace(); } } public static void b() throws ClassNotFoundException{ c(); } public static void c() throws ClassNotFoundException{ Class cls = Class.forName("java.lang.Integer"); System.out.println(cls.getName()); System.out.println(cls.isInterface()); } }
Trang 90
Lp trnh Java
X l bit l
Kt qu ca ThrowsDemo.java
Trang 91
Lp trnh Java
X l lung tp tin
Lp trnh Java
X l lung tp tin
V d: - Chng trnh mu sau lit k tp tin v th mc cha trong th mc lm vic hin hnh. import java.io.*; public class DirListing{ public static void main(String args[]){ File dir = new File(System.getProperty("user.dir")); if(dir.isDirectory()){ System.out.println("Directory of " + dir); String listing[] = dir.list(); for(int i=0;i<listing.length;i++) System.out.println("\t" +listing[i]); } } }
Lp trnh Java
X l lung tp tin
c dng trong vic kt ni mng, hay cc vng m ca b nh my tnh gip cho vic truy xut c nhanh.
Input Stream
Program
Output Stream
File
Chng trnh nhn d liu qua lung nhp v gi d liu qua lung xut C th xp lp lung vo hai loi: lung byte (byte stream) v lung k t (character stream). - Mi quan h phn cp ca lung byte thng dng:
FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream DataOutputStream OutputStream FilterOutputStream BufferedOutputStream ObjectOutputStream
FileWriter
Trang 94
Lp trnh Java
X l lung tp tin
2) Lung nhp xut c bn: a) Lp InputStream v lp Reader: - Lp tru tng InputStream v Reader, m rng Object, ln lt l lp gc (cha) ca mi lung nhp byte v k t. - Hai lp ny v lp con ca chng rt ging nhau, ngoi tr lp InputStream dng byte lm n v thng tin c bn, cn Reader s dng k t. Mt s phng thc thng dng trong InputStream: public int read() throws IOException - c byte tip theo v tr v gi tr ca n. Gi tr ca byte c tr v dng int, cui lung phng thc tr v -1. public int read(byte b[]) throws IOException - c cc byte b.length thnh mng b, gi tr tr v l s byte c c tht s. Cui lung tr v -1. public void close() throws IOException - ng lung nhp. public int available() throws IOException - Tr v s byte cn li trong lung. public long skip(long n) throws IOException B qua v loi b n byte d liu khi lung nhp ny. S byte tht s b b qua s c tr v. Lp Reader cha tt c phng thc va lit k, ngoi tr avalible (). b) Lp OutputStream v lp Writer: - C hai OutputStream v Writer ln lt l lp gc (cha) ca tt c lung xut byte v k t. Mt s phng thc thng dng trong OuputStream ln Writer: public void write(int b) throws IOException - Ghi mt byte (i vi OutputStream) hay mt k t (vi Writer) public void write(byte b[]) throws IOException - Ghi mi byte trong mng b sang lung xut (OutputStream) hoc mi k t trong mng k t (Writer) public void close() throws IOException - ng lung nhp. public void flush() throws IOException - Dn lung xut (c ngha gi d liu lu tm trong lung xut n ch ca n).
Trang 95
Lp trnh Java
X l lung tp tin
3) X l tp tin ngoi tr: Phi dng lung tp tin c hoc ghi vo tp tin a. Ta c th s dng: - FileInputStream hay FileOutputStream cho lung byte - FileReader hay FileWriter cho lung k t. Phng thc khi to sau: public public public public V d: FileInputStream infile = new FileInputStream ("c:\data\in.dat"); FileOutStream outfile = new FileOutStream ("c:\data\out.dat"); Ta cng c th s dng i tng tp tin to lung tp tin nh cu lnh sau: FileInputStream infile = new FileInputStream(new File ("c:\data\in.dat")); V d: - Chng trnh minh ha s dng FileInputStream v FileOutputStream sao chp tp tin. - Ngi dng cn cung cp mt tp tin ngun v tp tin ch lm i s dng lnh.
import java.io.*; public class CopyFile { public static void main (String args[]){ FileInputStream fis=null; FileOutputStream fos=null; if(args.length!=2){ System.out.println("Syntax is: java CopyFile sourcefile destfile"); System.exit (0); } try{ fis = new FileInputStream (args[0]); File outFile = new File (args[1]); if(outFile.exists()){ System.out.println("File " + args[1] + " already exists"); Trang 96
FileInputStream (String fileNameString) FileOutputStream (String fileNameString) FileReader (String fileNameString) FileWrite (String fileNameString)
Lp trnh Java return ; } else fos = new FileOutputStream(outFile); // Display the file size
X l lung tp tin
System.out.println("The file " + args[0] + " has " + fis.available() + " bytes"); int r; while((r=fis.read())!=-1) fos.write((byte)r); } catch(FileNotFoundException ex){ System.out.println("File not found " + args[0]); } catch(IOException ex){ System.out.println(ex.getMessage()); } finally{ try{ if(fis!=null) fis.close(); if(fos!=null) fos.close(); } catch(IOException ex){ System.out.println(ex.getMessage()); } } } }
Kt qu ca CopyFile.java
Trang 97
Lp trnh Java
X l lung tp tin
4) Lung lc: - Lung lc (filter stream) c nh ngha l lung lc cc byte hay k t nhm mc ch no . Lung nhp c bn cung cp phng thc c vn ch c th dng c byte hay k t. - Nu mun c s nguyn, s kp, chui, ta c th s dng lp lc bao bc mt lung nhp. Dng lp lc cho pho c s nguyn, s thc v chui thay v c byte v k t. Mt s lung lc thng dng:
Tn lp DataInputStream BufferedInputStream DataOutputStream BufferedOutputStream Cch dng lp X l dng thc nh phn cho mi loi d liu s cp Ly d liu t vng m v c d liu t lung, nu cn. Xut dng thc nh phn ca mi loi d liu s cp, vn rt hu ch nu chng trnh khc s dng u xut ny Xut sang vng m trc,sau sang lung, nu cn. Ta c th gi phng thc flush() ghi d liu vng m vo lung
5) Lung d liu: Lung d liu (DataInputStream v DataOutputStream) c v ghi dng d liu s cp. Phng thc khi to sau: public DataInputStream(InputStream instream) public DataOutputStream(OutputStream outstream) V d: DataInputStream infile = new DataInputStream(new FileInputStream(in.dat)); DataOutputStream outfile = new DataOutputStream(new FileOutputStream(out.dat)); Mt s phng thc thng dng: pubic int readByte() throws IOException pubic int readInt() throws IOException pubic long readLong() throws IOException pubic double readDouble() throws IOException pubic String readLine() throws IOException pubic void writeByte(byte b) throws IOException pubic void writeInt(int i) throws IOException pubic void writeLong(long l) throws IOException pubic void writeDouble(byte d) throws IOException
Trang 98
Lp trnh Java
X l lung tp tin
pubic void writeChars(String s) throws IOException V d: - Chng trnh minh ha to 10 s nguyn ngu nhin, lu chng vo tp tin d liu, truy xut d liu t tp tin v hin th s nguyn trn console. import java.io.*; public class TestDataStream{ public static void main (String args[]){ DataInputStream dis=null; DataOutputStream dos=null; // write data to file try{ dos = new DataOutputStream(new FileOutputStream( "mytemp.dat")); for(int i=0;i<10;i++){ dos.writeInt((int)(Math.random()*100)); } } catch(IOException ex){ System.out.println(ex.getMessage()); } finally{ try{ if(dos!=null) dos.close(); } catch(Exception ex){ } } // read data from file try{ dis = new DataInputStream(new FileInputStream( "mytemp.dat")); for(int i=0;i<10;i++){ System.out.print(" " + dis.readInt()); }
Trang 99
Lp trnh Java
X l lung tp tin
} catch(FileNotFoundException ex){ System.out.println("File not found"); } catch(IOException ex){ System.out.println(ex.getMessage()); } finally{ try{ if(dis!=null) dis.close(); } catch(Exception ex){ } } } }
Kt xut ca TestDataStream.java 6) Lung in n (PrintWriter): - V lung xut d liu hin th d liu dng nh phn, nn ta khng th xem ni dung ca n dng vn bn (Xem kt qu ca v d mc trc). - Trong Java, c th dng lung in n (print stream) xut d liu vo tp tin c xem dng vn bn. Phng thc khi to sau: public PrintWriter(Writer out) public PrintWriter(Writer out, boolean autoFlush) Mt s phng thc thng dng: pubic void print(Object o) throws IOException pubic void print(String s) throws IOException
Trang 100
Lp trnh Java
X l lung tp tin
pubic void print(int i) throws IOException pubic void print(long l) throws IOException pubic void print(double d) throws IOException pubic void print(boolean b) throws IOException - Ta c th thay th print bng println. Phng thc println() c chc nng in d liu, theo sau l mt dng mi. V d: - Chng trnh minh ha to 10 s ngu nhin v lu chng vo tp tin d liu vn bn mydata.dat. C th xem tp tin ny trn console bng lnh type trn Windows hay cat trn Linux. import java.io.*; public class TestPrintWriter{ public static void main(String args[]){ PrintWriter pw=null; // write data to file try{ pw = new PrintWriter(new FileOutputStream( "mydata.dat"),true); for(int i=0;i<10;i++){ pw.print( " " + (int)(Math.random ()*100)); } } catch(IOException ex){ System.out.println(ex.getMessage ()); } finally{ try{ if(pw!=null) pw.close (); } catch(Exception ex){ } } } }
Trang 101
Lp trnh Java
X l lung tp tin
Kt xut ca TestPrintWriter.java 7) Lung m: - Java tng tc nhp / xut da vo cc lung m (buffered stream), gim bt s ln c v ghi. - Dng lung m gip ta c th c / ghi mi ln mt khi byte hay k t thay v c tng byte hoc tng k t. Cc lp lung m trong java: - BufferedInputStream - BufferedOutputStream - BufferedReader - BufferedWriter Cc phng thc khi to lung m: public BufferedInputStream(InputStream in) public BufferedOutputStream(OutputSream out) public BufferedReader(Reader out) public BufferedWriter(Writer out) - Lp lung m tha k phng thc cc lp cha. Ngoi vic s dng phng thc t lp cha, BufferedReader cn c phng thc readLine () chu trch nhim c ni dung. V d: - Chng trnh mu minh ha xem tp tin trong vng vn bn. Khi ngi dng g tn tp tin vo trng vn bn v nhp nt View, tp tin s hin th trong vng vn bn. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class ViewFile extends JFrame implements ActionListener{ private JTextArea private JButton contentView; private JTextField txtInput; btnView;
Trang 102
Lp trnh Java
X l lung tp tin
public ViewFile(){ setTitle ("View File"); JPanel p = new JPanel(); p.setLayout (new FlowLayout (FlowLayout.LEFT)); p.add (new JLabel ("File name")); p.add (txtInput= new JTextField (20)); p.add(btnView = new JButton("View")); //register listener btnView.addActionListener(this); contentView = new JTextArea(20,30); JScrollPane pane = new JScrollPane(contentView); getContentPane().add(pane,BorderLayout.CENTER); getContentPane().add(p,BorderLayout.NORTH); } public void actionPerformed(ActionEvent e){ if(e.getSource()== btnView) showFile(); } public void showFile(){ BufferedReader inFile=null; String filename = txtInput.getText().trim(); String inLine; try{ inFile = new BufferedReader(new FileReader( filename)); boolean firstLine=true; while((inLine=inFile.readLine())!=null){ if(firstLine){ firstLine=false; contentView.append(inLine); } else contentView.append("\n" + inLine); } }
Trang 103
Lp trnh Java
X l lung tp tin
catch(Exception ex){ System.out.println(ex.toString()); } finally{ try{ if(inFile!=null) inFile.close(); } catch(Exception ex){ } } } public static void main(String args[]){ ViewFile frm = new ViewFile(); JFrame.EXIT_ON_CLOSE); frm.pack (); frm.setVisible (true); } } frm.setDefaultCloseOperation(
Kt xut ca ViewFile. java 8) Lp StreamTonkenizer: - phn tch c php v t dng mt cch mnh m v hiu qu hn ta cn s dng lp StreamTokenizer.
Trang 104
Lp trnh Java
X l lung tp tin
- Lp StreamTokenizer c kh nng nhn dng ra cc token trn lung. Nu hnh dung tp hp mt chui cc k t lm nn mt cu th token chnh l tng t, tng du chm cu hay con s. Phng thc khi to sau: public StreamTokenizer(InputStream in) Mt s phng thc thng dng: pubic int nextToken () throws IOException - Ly ra tng token, phng thc tr v mt trong nhng gi tr sau: StreamTokenizer.TT_WORD: token c c l mt t StreamTokenizer.TT_NUMBER: token c c l mt s StreamTokenizer.TT_EOL: c n cui dng StreamTokenizer.TT_EOF: c n cui lung. Lp StreamTokenizer c 2 thuc tnh: public String sval - Ly v gi tr ca token nu token c c l TT_WORD public double nval - Ly v gi tr ca token nu token c c l TT_NUMBER
Trang 105
Lp trnh Java
I. Khi nim:
1) Tuyn (Thread): L n v nh nht ca on m c th thi hnh c thc hin mt cng vic ring bit no . Nhng chng trnh trc y u chy mt tuyn; ngha l vo thi im xc nh ch c mt cu lnh c thc thi. 2) a tuyn (MultiThread): - L kh nng lm vic vi nhiu tuyn - a tuyn chuyn s dng cho vic thc thi nhiu cng vic ng thi - a tuyn gim thi gian ri ca h thng n mc thp nht v tng hiu sut thi hnh ca chng trnh. Tuyn c th c to ra bng 2 cch: - Dn xut t lp Thread - ng dng giao din Runnable. Chu k sng ca tuyn:
Dead
Trang 106
Lp trnh Java
Cu trc to 1 tuyn: class ThreadX extends Thread{ public void run(){ // ci t cng vic ca tuyn } ... } Thi hnh tuyn: ThreadX tx = new ThreadX(); tx.start(); Mt s phng thc thng dng trong lp tuyn: public void run() - Phng thc c h thng gi thc thi cng vic ca tuyn, ta phi ginh quyn phng thc ny v cung cp m cho tuyn thi hnh. - Phng thc run() khng c gi trc tip t i tng Thread. public void start() - Khi ng tuyn, qua lm cho phng thc run() cng c kch hot. public static void sleep(long millis) throws InterruptedException - t tuyn vo trng thi ng trong khong thi gian xc nh bng mili giy. public void stop() - C chc nng ngng tuyn. public void join() throws InterrupteException - Ch i tuyn ny cht i. public void setPriority(int p) - n nh quyn u tin p(xp t 1 n 10) cho tuyn ny. V d: - Chng trnh ny to v chy 2 tuyn sau: Tuyn th nht in cc s nguyn t 1 n 10. Tuyn th hai in ch A 10 ln. package chapter07; class PrintNum extends Thread{ public void run(){ for(int i=1;i<=10;i++){ System.out.print(" " + i); try{
Trang 107
Lp trnh Java
Thread.sleep(300); }catch(Exception ex){} } } } class PrintChar extends Thread{ public void run(){ for(int i=1;i<=10;i++){ System.out.print(" A "); try{ Thread.sleep(300); } catch(Exception ex){ } } } } public class TestThread{ public static void main(String args[]){ PrintNum t1= new PrintNum(); PrintChar t2= new PrintChar(); t1.start(); t2.start(); try{ t1.join(); t2.join(); } catch(Exception ex){ } System.out.println("\n Both thread is deaded"); } }
Trang 108
Lp trnh Java
Kt qu ca TestThread.java 2) To tuyn bng cch ng dng giao din Runable: - phn trc, ta to v chy tuyn thi hnh bng cch khai bo mt lp tuyn m rng lp Thread. Phng thc ny s c hiu lc nu lp tuyn ch k tha t lp Thread, nhng s v dng khi lp tuyn tha k nhiu lp. tha k nhiu lp, ta phi ng dng giao din.Java cung cp giao din Runnable thay th lp Thread. Cu trc nh ngha 1 tuyn: class RunnableY implements Runnable { public void run(){ // process Threads } ... } Thi hnh tuyn: RunnableY ry = new RunnableY(); Thread ty = new Thread(ry); tx.start(); V d: - Chng trnh mu nh ngha mt tuyn hin th thi gian (hh:mm:ss) trong mt panel. - Tp tin ClockPanel.java package chapter07; import javax.swing.*; import java.awt.*; import java.util.*; import javax.swing.border.*; public class ClockPanel extends JPanel implements Runnable{ private JTextField txtDisplay; private Thread t;
Trang 109
Lp trnh Java
public ClockPanel(){ add(new JLabel("Time is")); add(txtDisplay= new JTextField(20)); setBorder(new TitledBorder(new EtchedBorder(),"Clock")); } public void run(){ String msg=""; while(true){ Date today = new Date(); msg = today.getHours() + ":" + today.getMinutes()+":" + today.getSeconds(); txtDisplay.setText(msg); try{ Thread.sleep(1000); }catch(Exception ex){ } } } } // TestClock.java package chapter07; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.border.*; public class TestClock extends JFrame implements ActionListener{ JButton btnStart,btnStop; ClockPanel p1 = new ClockPanel(); Thread t; public TestClock(){ setTitle("Test clock"); getContentPane().add(p1,BorderLayout.NORTH); JPanel p2 = new JPanel();
Trang 110
Lp trnh Java
p2.add(btnStart = new JButton("Start")); p2.add(btnStop = new JButton("Stop")); getContentPane().add(p2,BorderLayout.CENTER); btnStart.addActionListener(this); btnStop.addActionListener(this); btnStop.setEnabled(false); } public void actionPerformed(ActionEvent e){ if(e.getSource()==btnStart){ start(); btnStart.setEnabled(false); btnStop.setEnabled(true); } else if(e.getSource()==btnStop){ stop(); btnStart.setEnabled(true); btnStop.setEnabled(false); } } public void start(){ t = new Thread(p1); t.start(); } public void stop(){ if(t!=null){ t.stop(); } } public static void main(String args[]){ TestClock frm =new TestClock(); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.pack(); frm.setVisible(true); }
Trang 111
Lp trnh Java
Kt qu ca TestClock.java
Trang 112