java_ease_learning

Upload: mai-trung

Post on 08-Apr-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Java_ease_learning

    1/47

    CHNG I - BT U VI JAVA

    Bi 1 Hello worldBn hy xem bi ca anh CEO trong JVN

    Bi 2 In ra chui nhp voBi u tin ca bn, bn hc cch Java in ci g ra mn hnh, trong bi ny,bn s hc cch nhp vo ci g v Java in ci ra mn hnh. G ci ny i bn(lu , bn phi g, khng c copy v paste)import java.io.*;public class Hello {

    public static void main(String[] args) throws Exception {BufferedReader in = new BufferedReader(new

    InputStreamReader(System.in));System.out.print("Your name is: ");String str;str = in.readLine();System.out.println("Welcome " + str + " to Java");

    }}

    Xin hi, ti bt u vi mt vi v d, m tichng hiu ci g c.Xin tr li, bn s hc Java qua cc v d, rt nhiu v d, l thuyt th bn ch hc t tthi.

    *L thuyt: cu trc mt chng trnh Javapublic class Core {

    public static void main(String[] args) {System.out.println("Hello,Everybody in the World!");

    }}

    public class Core bn bt u mt lp Javapublic static void main(String[] args) y l mt phng thc main trong Java, chochng trnh chy c. Tm thi bn phi g y nh th nySystem.out.println("Hello,Everybody in the World!") y l mt cu lnh trong Java,n gin n ch in ra chui nm trong 2 du ra mn hnh.Mi lp v phng thc trong Java m ra bng { v ng li bng }Mi cu lnh trong java kt thc bng ;

    Bi 3 Bin trong Java

    import java.io.*;public class Hello {

    public static void main(String[] args) throws Exception {BufferedReader in = new BufferedReader(new

    InputStreamReader(System.in));

  • 8/7/2019 Java_ease_learning

    2/47

    System.out.print("Nhap a: ");int a = Integer.parseInt(in.readLine());System.out.print("Nhap b: ");int b = Integer.parseInt(in.readLine());int ketqua;ketqua = a+b;System.out.println("Ket qua bai toan a+b la: + ketqua);

    }}

    Nhp th 2 s a v b vo i bn, kt qu bi ton a+b s c in ra.

    *L thuyt:import java.io.*;public class Hello {

    public static void main(String[] args) throws Exception {BufferedReader in = new BufferedReader(new

    InputStreamReader(System.in));System.out.print("Your name is: ");

    String str;str = in.readLine();System.out.println("Welcome " + str + " to Java");

    }}

    Tm thi, trong chng trnh ny, bn ch nn quan tm n dngString str khai bo bin str kiu chui, vSystem.out.println("Welcome " + str + " to Java")

    y cng l dng System.out.println nh chng trnh u, c khc l + str+ tc la mt bin vo chui in ra. Ch n thi nh, sau , hy quan tm n bi hm

    naySystem.out.print("Nhap a: ");

    int a = Integer.parseInt(in.readLine());

    System.out.print("Nhap b: ");

    int b = Integer.parseInt(in.readLine());

    int ketqua;

    ketqua = a+b;

    System.out.println("Ket qua bai toan a+b la: + ketqua);

    *Gii thchimport bn nhp class hay th vin chun, tm thi ng quan tm n l g, ch cnnh l c n chng trnh chySystem.out.print in ra mt chui, nhng khng xung dngSystem.out.println in ra mt chui, nhng xung dngint ketqua tc l khai bo bin ketqua kiu int

  • 8/7/2019 Java_ease_learning

    3/47

    ketqua = a+b tc l gn kt qu mt biu thc tnh ton ( y l bin a + bin b) chobin ketquaSystem.out.println("Ket qua bai toan a+b la: + ketqua) th n gin ri, in ci dng ra, ch khc l n a bin ketqua ca bn vo chui .

    Bi 4 Chia ht, chia ly d

    *L thuyt: mt s kiu bin trong Java

    Bn bit 2 kiu String (chui) v int (nguyn) by gi bn bit thm kiu float (thc)S nguyn v s thc bn bit s khc nhau ri ch. By gi ta bt u bi ton v dimport java.io.*;public class Hello {

    public static void main(String[] args) throws Exception {

    BufferedReader in = new BufferedReader(newInputStreamReader(System.in));System.out.print("Nhap a: ");float a = Float.parseFloat(in.readLine());System.out.print("Nhap b: ");float b = Float.parseFloat(in.readLine());float ketqua = a/b;System.out.println("Ket qua bai toan a+b la: " + ketqua);

    }}

    Bn th bi ton xem, nh ng nhp s b=0 nh, chuyn y s x l sau.V d nhp a=5, b=2, kt qu in ra s l 2.5, th v phi khng ?

    By gi cng bi ton y, bn thay i nh sau:import java.io.*;public class Hello {

    public static void main(String[] args) throws Exception {BufferedReader in = new BufferedReader(new

    InputStreamReader(System.in));System.out.print("Nhap a: ");int a = Integer.parseInt(in.readLine());System.out.print("Nhap b: ");int b = Integer.parseInt(in.readLine());float ketqua = a/b;System.out.println("Ket qua bai toan a+b la: " + ketqua);

    }}

    Cng nhp a=5, b=2, ln ny kt qu in ra l 2Php chia s l php chia ht nu c 2 ton hng u kiu nguyn, gi l chia lynguyn (/) hay div

  • 8/7/2019 Java_ease_learning

    4/47

    By gi cng chng trnh y m ta thay i li cht xu xem saoimport java.io.*;public class Hello {

    public static void main(String[] args) throws Exception {

    BufferedReader in = new BufferedReader(newInputStreamReader(System.in));

    System.out.print("Nhap a: ");int a = Integer.parseInt(in.readLine());System.out.print("Nhap b: ");int b = Integer.parseInt(in.readLine());float ketqua = a%b;System.out.println("Ket qua bai toan a+b la: " + ketqua);

    }}

    Cng nhp a=5, b=2, ln ny kt qu in ra l 1y l kt qu php chialy d 5 chia cho 2, gi l chia ly d (%) hay mod

    *Th nu ti mun 2 s nguyn chia nhau m ra kiu thc ch khng phi php chialy nguyn th sao ? Trong trng hp , bn dng p kiuint a=5,b=2;float ket qua;

    ketqua=(float)a/b;

    Bi 5 Lp trnh OOPBn xem bi ca anh CEO trong JVNclassy l mt class, class ny c hai property (thuc tnh) l name v agepublic class Person{

    String name;int age;

    }

    y l mt class, class ny ngoi property cn c constructor (khi to) ca class public class Person{

    String name;int age;public Person(String name){

    this.name = name;}

    }

    Trong ci constructor ny hy lu mt iu, l bin this. Bin this c ngha l bnthn ci class ( y l class Person).

  • 8/7/2019 Java_ease_learning

    5/47

    Trong class Person c mt property l age, cu this.age = age c ngha l ci thuc tnhage ca class Person s nhn gi tr ci i s age do constructor Person(int age) avo.Lu l mi class u c sn t nht mt constructor khng c i s.y l mt class, class ny ngoi property, constructor cn c mt behavior (hnh vi)public class Person{

    String name;int age;public Person(int age){

    this.age = age;}public void Nhap(){

    nameonsole.readLine("Nhap ho ten:");}

    }

    Khi ta vit cu lnh sauPerson personOne = new Person(12);

    Th ta to ra mt instance (th hin) l personOne ca class Person

    Khai bo mt class

    public abstract class MyClass {}

    T th 1 l khai bo quyn truy xut v k tha,c 3 loi-public:c php truy xut t bt c ni no v bt c lp no cng c quyn ktha-protected:ch c phng thc cng gi c php truy xut v k tha-private:ch c phng thc cng gi c php truy xut nhng khng lp no cphp k tha-nu khng khai bo,mc nh l protected

    T th 2 l khai bo mt lp tru tng hay l khng tru tng

    Nhiem vu: tao 1 lop Person, tao tiep 2 lop Students va Teachers ke thua lop Person, tao

    lop Execute chua ham chinh de chay chuong trinh.

    --lop Person-import corejava.*;abstract class Person{

    //cai nay goi la cac property hay state-thuoc tinh cua doi tuongString hoten;int age;

  • 8/7/2019 Java_ease_learning

    6/47

    String diachi;int luong;//cac constructorpublic Person(int age){

    this.age = age;}//cac method hay behavior-hanh vi cua doi tuongpublic void Nhap(){

    hoten = Console.readLine("Nhap ho ten:");diachi = Console.readLine("Nhap dia chi:");

    }//vi la 1 class thuoc loai abstract nen Person duoc phep khai bao cac

    method khong co noi dung, noi dung cua class In se duoc cac lop ke thua nothem vao noi dung cua rieng no

    public abstract void In();public abstract int Tinhluong();

    }

    --lop Students-import corejava.*;class Students extends Person{

    int MaSV,Malop;public void Nhap(){

    super.Nhap();MaSV = Console.readInt("Nhap ma SV:");Malop = Console.readInt("Nhap ma lop:");

    }public void In(){

    System.out.println(hoten);System.out.println(diachi);System.out.println(MaSV);System.out.println(Malop);

    }public int Tinhluong(){return 150000;}

    }

    tu khoa super se goi ham Nhap() tu lop Person la cha cua lop Students

    --lop Teachers-import corejava.*;class Teachers extends Person{

    int Makhoa;public void Nhap(){

    super.Nhap();Makhoa = Console.readInt("Nhap ma khoa::");

    }

  • 8/7/2019 Java_ease_learning

    7/47

    public void In(){

    System.out.println(hoten);System.out.println(diachi);System.out.println(Makhoa);

    }public int Tinhluong(){

    return 500000;}

    }

    --lop Execute-import corejava.*;class Execute{

    public static void main(String args[]){

    Students st = new Students();st.Nhap();st.In();st.luong=st.Tinhluong();Teachers tc = new Teachers();tc.Nhap();tc.In();tc.luong=tc.Tinhluong();

    }}

    Khai bo mt thuc tnh:

    public static void temp;

    T th 1 l khai bo quyn truy xut,c 3 loi-public:c php truy xut t bt c ni no-protected:ch c lp con mi c php truy xut-private:ch c lp xi(thuc tnh ring ca n)-nu khng khai bo,mc nh l protected

    T th 2 l khai bo cch truy xut static(tnh)

    -nu khng khai bo,mc nh l khng tnhTt c cc i tng th hin t lp cha u c php thay i gi tr ca cc thuctnh khng tnh,cn gi tr ca thuc tnh tnh th khng c php thay ipublic class Car{

    public string branch;public int cost;

  • 8/7/2019 Java_ease_learning

    8/47

    public static int tire=4;}

    Nh v d trn,tt c cc lp con ca lp Car (nh ToyotaCar,Peugeot,Mazda) uc php thay i cc thuc tnh branch hay cost ph hp cho ring mnh,nhngthuc tnh tire (s bnh xe) khng c php thay i v l thuc tnh tnhNi cch khc, ch c mt v ch mt thuc tnh c tn l tire trong class Car v tt ccc class con ca n, v vy gi l tnh

    Khai bo mt hnh viMt phng thc c khai bo nh saupublic static double ketqua()

    C 3 ch nh truy xut l public, protected v private-public:c php truy xut t bt c ni no-protected:ch c lp k tha lp cha n c truy xut

    -private:ch lp cha n c truy xut(dng ni b)-nu khng khai bo,mc nh l protected

    C 6 ch nh thuc tnh l static,abstract, final, native, synchronized (ng b) vvolatile (linh hot), static(tnh)

    -nu khng khai bo,mc nh l khng tnhclass TestObject{

    static void StaticMethod() {}void NonStaticMethod() {}

    }

    Nu l mt phng thc khng tnh, u tin bn phi khi to mt i tng,sau mi c php gi phng thcTestObject test=new TestObject();

    test.NonStaticMethod();

    Nu l mt phng thc tnh,bn c php gi trc tip t lpTestObject.StaticMethod();

    abstract(tru tng)Mt phng thc tru tng khng c ni dung.Ni dung ca n s c cc lp con

    ty bin v pht trin theo hng ca ring n.- final: khng th c extends hay override (ghi )- native: thn phng thc vit bng C hay C++- synchronized: ch cho php 1 thread truy cp vo khi m cng mt thi im- volatile: s dng vi bin thng bo rng gi tr ca bin c th c thay i viln v vy khng ghi vo thanh ghi

  • 8/7/2019 Java_ease_learning

    9/47

    T th 3 l gi tr tr v.Nu khng c gi tr tr v th l void

    Interface-template

    By gi ta c 1 khi nim mi, l giao din. Giao din ra i chnh l gii quyt a

    k tha. Mi lp trong Java ch c 1 lp cha, nhng c th implements nhiu giao din.Giao din c khai bo ging nh 1 lp, cng c state v behavior. Nhng state cagiao din l final cn behavior l abstractGi s, ta s khai bo mt giao dinpublic interface Product{

    //hai state duoi day la final, tuc la lop implements khong duoc phepdoi gia tri

    static string maker = My Corp;static string phone = 555-7767;//behavior duoi day la abstract, tuc la khong co noi dungpublic int getPrice(int id);

    }

    By gi, ta s vit mt class c ci t (implements) giao din nypublic class Shoe implements Product{

    public int getPrince(int id){

    return (id= =1)?5:10;}public String getMaker(){

    return maker;}

    }

    Mun implements nhiu giao din, lm nh sau, v d class Toyota extends Carimplements ActionCar, ActionMobilation

    package-unitHy to 1 th mc c tn l TransportBn trong th mc ny hy to 2 file l Car.java v Bicycle.java nh sau

    --Car.java-package Transport;public class Car

    { public String manufacturer;public int year;

    }

    --Bicycle.java-package Transport;public class Bicycle{

    public int cost;public Bicycle(int cost)

  • 8/7/2019 Java_ease_learning

    10/47

    {this.cost = cost;

    }}

    Nh vy l ta to ra 1 gi cha 2 lp l Car v Bicycle. By gi ta c 1 chng trnh

    mun s dng gi ny l TestProgram.java. Ta vit:

    --ViDuTransport.java-import Transport.*;class TestProgram{

    public static void main(String args[]){

    Car myCar = new Car();myCar.manufacturer = Toyota;Bicycle myBicycle = new Bicycle(1500);

    }}

    Lu nu trong file ViDuTransport bn khng khai bo import Transport.* th bn vnc th khai bo tng minh nh sauTransport.Car myCar = new Transport.Car();

    np chng (overload) 1 phng thcclass Vidu{

    public satic void main(String a[])

    {private float cost;public float CalculateSalePrice(){

    return cost*1.5;}public float CalculateSalePrice(double heso){

    return cost*(1+heso);}

    }}

    y c 2 phng thc trng tn CalculateSalePrice nhng phng thc th 2 khctham s, gi l np chng* np chng (overload) v ghi (override)Nhng phng thc c np chng l nhng phng thc trong cng mt lp, ccng mt tn nhng danh sch i s khc nhauPhng thc c ghi l phng thc c mt lp cha, c xc nh l phngthc chung cho cc lp con, ri xut hin cc lp con

  • 8/7/2019 Java_ease_learning

    11/47

    Np chng l mt hnh thc a hnh (polymorphism) trong qu trnh bin dch (compile)cn ghi l trong qu trnh thc thi (runtime)

    Bi 6 Cc kiu dliu nguyn thy v php ton

    - Kiu nguyn: gm snguyn(int,long)- Kiu du phy ng (hay kiu thc): gm sthc(float,double)- Kiu k t(char)- Kiu chui (String)

    Hng k tkhai bo nh sau, v d 'H' (khc vi "H" l mt chui k t)Mt shng k tc bit, v d '\\' biu din chnh k t\, v \u biu din Unicode, v d:

    '\u00B2' biu din (bnh phng)'\u00BC' biu din (mt phn t)'\u0170' biu din (m a)- Kiu booleanC 2 gi tr l 2 tkha true v false, v khng thchuyn kiu sang int

    *Khai bo binint i,j; //2 bin i v j c kiu dliu l intchar ch='A'; //bin ch kiu char khi to gi tru 'A'

    *Khai bo hngHng c khai bo vi tkha final. V d:final float PI = 3.14159;

    *Php ton

    Php ton ca Java ging C. Trong class java.lang.Math c mt smethod dng trong tonhc nh saudouble y = Math.pow(x,a) = x

    v random, sin, cos, tan, exp (m), log(logarit) ...

    * Cc php ton shc- Vi c kiu nguyn v kiu thc: + - * / (php chia s cho ra kt qu kiu thc nu mt trong2 ton tl kiu thc)- Chia ht (/) ch p dng khi c 2 ton tl kiu nguyn, v d 10/3=3

  • 8/7/2019 Java_ease_learning

    12/47

    - Chia ly d (%) ch p dng khi c 2 ton tl kiu nguyn, v d 10%3=1

    * Cc php ton quan h (so snh)- Bao gm ==,,= tr v kiu boolean

    * Cc php ton vi kiu logic- Bao gm and(k hiu &&) or(k hiu ||) not(k hiu !)

    * Php ++ v --

    - Php ny c 2 dng, mt l ++bin hay --bin, hai l bin++ hay bin-- Skhc nhau ch lkhi php ny thc hin chung vi mt php ton khc th- Vi ++bin v --bin th n s thc hin php ton ny trc ri mi thc hin php tonkhc

    - Vi bin++ v bin-- th n s thc hin php ton khc trc ri mi thc hin php tonny

    * Php gn

    - Php ny c dng a=5- Php gn phc, v da+=5 ngha l a=a+5, hay a*=2 ngha l a=a*2

    * Trnh tkt hpHu ht cc php ton iu c trnh tkt hp ttri sang phi, ch c cc php sau l tphisang tri

    - Php ++ v --

    - Cc php gn nh =,+=,-=,=

    Bi 7 Mnh if

    nu em p th ti s ca em khng th ti ca a khcIF em p THEN ti s ca em ELSE ti ca a khc

    IF(em p) ti s ca em;ELSE ti ca a khc;

    C php (syntax) ca mnh IF lif(mnh ) lnh 1;else lnh 2;Nu mnh ng th thc hin lnh 1;

  • 8/7/2019 Java_ease_learning

    13/47

    Khng th thc hin lnh 2;

    V dif(a>b) System.out.println(So lon nhat la +a);else System.out.println(So lon nhat la +b);

    *Ta xy dng mt bi ton lm trn sNhp vo mt s bt k. Nu phn thp phn s ny >=0.5, lm trn tng ln mt nv, ngc li gim i mt n v.import java.io.*;public class Hello {

    public static void main(String[] args) throws Exception {BufferedReader in = new BufferedReader(new

    InputStreamReader(System.in));System.out.print("Nhap a: ");float a = Float.parseFloat(in.readLine());float ketqua=a%1;if(ketqua>=0.5) a=a-ketqua+1;else a=a-ketqua;System.out.println("Ket qua bai toan la: " + a);

    }}

    * Php iu kin ? v php chn :- Gi s c mnh ifif(a>b) a=2;else a=0;Php iu kin biu din nh sau a=a>b?2:0 ngha l nu chn tr ca a>b l ng tha=2 nu l sai th a=0

    * Sau khi hc xong if, bn c rt nhiu bi tp m lm, c in nht vn l giiphng trnh bc mt v hai, ngoi ra cn nhiu bi tp khc na. y ch c giiphng trnh bc mt. Bn nn tm nhiu bi tp t lm trc khi tip tc phn k.

    V d: phng trnh bc 1import java.io.*;public class Hello {

    public static void main(String[] args) throws Exception {BufferedReader in = new BufferedReader(new

    InputStreamReader(System.in));System.out.println("Giai phuong trinh bac nhat dang ax+b=0");

    System.out.print("Nhap he so a: ");float a = Float.parseFloat(in.readLine());System.out.print("Nhap he so b: ");float b = Float.parseFloat(in.readLine());if(a==0) {

    if(b==0) System.out.println("Phuong trinh vo songhiem");

    if(b!=0) System.out.println("Phuong trinh vo dinh");}else System.out.println("Phuong trinh mot nghiem x=" + -b/a);

  • 8/7/2019 Java_ease_learning

    14/47

    }}

    Bi 8 switch

    Bn hc xong if. Bn mun dng vng lp if nh gi im s nhp vo. Bn svit chng trnh sau yimport java.io.*;public class Hello {

    public static void main(String[] args) throws Exception {BufferedReader in = new BufferedReader(new

    InputStreamReader(System.in));System.out.print("Nhap diem so: ");int diem = Integer.parseInt(in.readLine());if(diem2) && (diem3) && (diem4) && (diem

  • 8/7/2019 Java_ease_learning

    15/47

    Khc vi C, String l mt lp ca Java. String c khai bo nh sauString a = "Hello";

    Cng 2 String bng du +System.out.println("Gia tri la " + n);

    Java c khnng tchuyn kiu bt cdliu kiu sno khi cng vo String. D n l int,float, double u c thchuyn thnh String nh mo vt ("" + n)

    Cc method trong class String

    * substring

    String s1 = "Hello";

    String s2 = s1.substring(0,4); //bt u tk tth0 (tc l 'H') ly i 4 k t(tc l "Hell")

    * length

    int n = s1.length(); //tc l bng 5

    * charAt

    char ch = s1.charAt(4); //tc l bng 'o'y l method tm k tthi trong String, cc k ttrong String c nh st0

    * equals

    Kiu tra xem chui ngun s c ging chui ch d hay khng, ta dng method equals tr v

    booleanboolean b = s.equals(t);

    String khng ging dliu kiu s, tuyt i khng dng ging nh if(s==t)

    * compareTo

    int a = s2.compareTo(s1);

    a>0 s2>s1

    a

  • 8/7/2019 Java_ease_learning

    16/47

    * indexOf

    String s1 = "Hello Everybody";

    String s2 = "lo";

    int n = s1.indexOf(s2); //n s bng 4y l method tr v v tr ca chui s2 trong chui s1, nu khng tm thy s tr v -1

    * Chuyn kiu tString ra dliu kiu sChuyn tdliu kiu sra String kh ddng, dng "" + n, nhng ngc li th phi dngcc method tng ng.Cc method ny nm trong gijava.lang, trong cc class Byte, Short, Integer, Long, Float,Double

    String input = "230";

    int n = Integer.parseInt(input); //n s bng 230Tng tvi cc method sau Byte.parseByte, Short.parseShort, Float.parseFloat, ...

    Bi 10 vng lp for

    for(int i=0;i

  • 8/7/2019 Java_ease_learning

    17/47

    Bi 11 whilewhile(biu thc)

    lnh;Nu biu thc ng th thc hin lnh*break vi while: break s thot ngay ra khi vng whileint i=0;while(i

  • 8/7/2019 Java_ease_learning

    18/47

    Ta s c mt lot in 0 v tn

    Bi 13 array

    Ta khai bo 1 mng vi cu lnh sau, v khng cung cp sphn tint[] a;

    Tuy vy, vi Java, dng c mt array, ta cn phi khi to array , v lc ny phi cungcp sphn tint[] a;

    a = new int[100];

    Hai cu c thvit li thnh mt cuint[] a = new int[100];

    Java s khi to mt mng 100 phn tu l int c nh thtt0 n 99Mng c gi tru: Mng loi ny khng cn new m cng chng cn sphn tint[] a = {1,45,6,8,21};

    Cc method vi mng* length

    method ny s cung cp sphn tca mng, v d ta mun gn gi tr scho cc phn tca mng afor(int i=0;i

  • 8/7/2019 Java_ease_learning

    19/47

    Arrays.sort(s);

    * int binarySearch

    N s tm v tr ca mt phn ttrong mt mng, tr v -1 nu khng tm thy

    int[] s = {28,7,14,11};int n = Arrays.binarySearch(s,14); n s bng 2

    Mng nhiu chiuint[][] = new int[100][50];

    Hoc khai bo 1 mng c gi tru. y l mng 2 chiu gm 4 phn tl 4 mng 1 chiu,mi mng 1 chiu cha 3 phn tint[][] a =

    {

    {16, 3, 2},

    {5, 10, 11},

    {9, 6, 7},

    {4, 15, 14}

    };

    Bi 14 - ngoi lint x,y;x=10;y=x-10;x=x/y;

    Khi chy on m ny bn s thy xut hin thng bojava.lang.ArithmeticException: divide by zeroV chng trnh s thot ra ngay lc . Mun chng trnh chy tip v khng thotra, ta n "bt" ngoi l ny, a ra bin e, cuicng in e ( xem l ngoi l g)int x,y;try{

    x=10;y=x-10;x=x/y;

    }catch(Exception e){

    System.out.println(e.getMessage());}

    X l ngoi l (Exception) "nm" ngoi l do bt c dng m no trong mt phng thc sinh ra, bn c thkhai bo nm b ngoi l public void divide() throws Exception{

  • 8/7/2019 Java_ease_learning

    20/47

    int a=5/0;}

    hoc nu mun "bt" ngoi l li xem l ngoi l g x l, bn "bt" n riin ratry{

    int a=5/0;}catch(Exception e){

    System.out.println(e.getMessage());}

    Nu mun chng trnh thnh cng th sinh thng bo thnh cng, tht bi th sinhthng bo ngoi l, bn c th dngboolean done=false;try{

    int a=5/b;

    done=true;}catch(Exception e){

    System.out.println(e.getMessage());}if(done==true) System.out.println("Successful");

    Bi 15 - Vector (mng khng gii hn sphn t)

    Cc method trong bi ny nm 2 class java.util.Vector v java.util.EnumerationKhai bo

    Vector vt = new Vector();

    Nhp dliu cho mt Vector (class Console nm trong gi corejava)Lu l mi phn tca Vector u phi l mt i tng, nn ta phi c new Integer(n) khimun a vo mt bin kiu int. Tng tvi Byte, Long, Float, ...do

    {

    int n = Console.readInt("");

    if(n!=0) vt.addElement(new Integer(n));}

    while(n!=0);

    In ra cc phn t ca mt Vector

    for(int i=0;i

  • 8/7/2019 Java_ease_learning

    21/47

    Enumeration e = vt.elements();

    Nh vy ta c mng e kiu Enumeration sao chp y khun Vector vt d xl, khng ngn Vector vtIn ra cc phn tca mt Enumerationwhile(e.hasMoreElements())

    System.out.println(e.nextElement());

    Bi 16 - Lp ni (lp nm trong lp khc)

    public class TestProgram{

    static int currentCount;static class Apple{

    int weight;public Apple(int weight)

    {this.weight=weight;currentCount++;

    }public int Weight(){

    return weight;}

    }public static void main(String args[]){

    Apple a=new Apple(12);//khoi tao 1 qu tao nang 12kgSystem.out.print(a.Weight());

    }}

    y ta thy lp ni Apple trong lp TestProgram, khi bin dch Java s lm xut hin2 file l TestProgram.class v TestProgram$Apple.class. u im khi s dng lp ni l:- th hin tnh ng gi cao- cc lp ni c th truy xut trc tip cc bin ca lp chaLu l lp ni khc vi cc lp m nm chung mt file, v d nh tp tinMainClass.java di ypublic class MainClass{}

    class Subclass{}

    Bi 17 - To tp tin jar tchy

    Gi schng trnh ca bn c vi file .class trong file chng trnh chnh l MainPro.class

  • 8/7/2019 Java_ease_learning

    22/47

    chng hn.Bn hy to mt file ly tn l mymf.mf c ni dung nh sauMain-Class: MainPro

    Bt buc phi chnh xc nh th(tc l phi c c xung dng), khng th trnh chy jar khng

    hiu c.Sau bn vo %JAVA_HOME%\bin\ chp tt c cc tp tin .class ca ng dng v cmymf.mf vo , ri chy jar.exe vi tham sdng lnh nh saujar cmfv mymf.mf MyProgram.jar *.class

    Tng tnu bn mun a thm 2 th mc dir1 v dir2 v file JAR th bn cng gjar cmfv mymf.mf MyProgram.jar *.class dir1 dir2

    Trnh jar s to file MyProgram.jar (tn khc ty bn) c thchy c, khng phi dng lnhjava hay gi skhng c IDE quen thuc ca bn

    CHNG 2 - JAVA V LP TRNH GIAO DIN BNG SWING

    n lc bn nn s dng mt IDE cng vic ca mnh nhanh chng v d dnghn. Applet tr thnh c, chng ta nhy lun sang AWT Swing

    Bi 1 - M u v Swing

    Chng trnh ny s to mt JFrame n gin nhtimport javax.swing.JFrame;class HelloWorldSwing{

    public static void main(String[] a){

    JFrame frame=new JFrame("Main Frame");//Main Frame la ten caicua so

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//hamdong cua so lai

    JLabel label=new JLabel("Hello Everybody, label containcontext");//mot doi tuong do hoa

    frame.getContentPane().add(label);//dua doi tuong do hoa vaotrong frame

    frame.pack();//"dong goi" lai toan bo trinh do hoaframe.setVisible(true);//hien thi trinh do hoa ra man hinh

    }

    }

    y l mt Frame n gin khc, nhng c th dng d dng cho vic m rng chngtrnhimport javax.swing.JFrame;import java.awt.*;class Execute extends JFrame{

    Container container = getContentPane();

  • 8/7/2019 Java_ease_learning

    23/47

    public Execute(String title){

    super(title); //tuong duong JFrame(title)Label label=new Label("Hello Everybody, label contain

    context");container.add(label);

    }public static void main(String a[]){

    Execute exe = new Execute("Frame");exe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);exe.pack();exe.setVisible(true);

    }}

    H tr ting VitGi s bn mun nt bm ca bn c dng "Vit Nam" v bn khng bit in nh thno, chng trnh sau s gip bnJButton b=new JButton("Vi\u1EC7t Nam");

    \u1EC7 l m Unicode ca k t m Java h tr. Tt c k t Vit u c h trtrong Latin v Latin Extend

    Lu l ch c javax.swing mi h tr, java.awt khng h tr

    Bi 2 - Ci t b nghe v s kin cho cc i tng ha

    Cc i tng ha s d c th hot ng c l nh c cc b nghe "nghe" cc

    hnh ng m ngi dng tng tc vi chut hay bn phm, v t cho ra cc skin tng ng.Trong v d di y ta c class EventQuit l mt b nghe, b nghe ny thc hinphng thc actionPerformed chnh l cha nhng s kin ca b nghe . i tngeventQuit l mt instance ca class EventQuit. ci t b nghe ny cho i tng ha button ta dng phng thc addActionListener.import javax.swing.JFrame;import java.awt.*;import java.awt.event.*;class Core extends JFrame{

    Container container = getContentPane();

    public Core(String title){

    super(title);Button button = new Button("My button");EventQuit eventQuit=new EventQuit();button.addActionListener(eventQuit);container.add(button);

    }public static void main(String a[]){

  • 8/7/2019 Java_ease_learning

    24/47

    Core exe = new Core("Frame");exe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);exe.pack();exe.setVisible(true);

    }class EventQuit implements ActionListener{

    public void actionPerformed(ActionEvent e){

    System.exit(0);}

    }}

    By gi, nu ta mun rt gn, ci t b nghe v hnh ng trc tip, ta lm nh sauimport javax.swing.JFrame;import java.awt.*;import java.awt.event.*;class Core{

    public static void main(String args[]){

    JFrame frame = new JFrame("My frame");final JButton button = new JButton("My button");button.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e){

    if(e.getSource()==button) System.exit(0); //nuevent ny c source do button sinh ra

    }});frame.add(button);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.pack();frame.setVisible(true);

    }}

    Bi 3 - setLayout(null) i i vi setBounds

    setLayout mnh nht trong Swing l setLayout(null) cho i tng add, cn i vi itng b add th setBounds, c php setBounds(x,y,width,height)Trn monitor, Java tnh im c ta (0,0) l im tri trn cng. Sau trc honh

    (x) l chiu ngang monitor t tri sang phi v trc tung (y) l chiu dc monitor ttrn xung diPhng thc ny s to ra mt hnh ch nht o bao quanh i tng b add, hnh chnht ny c ta gc u tin l (x,y) v di width cao height. V d nh bi sau:import javax.swing.JFrame;import java.awt.*;class Core{

    public static void main(String args[])

  • 8/7/2019 Java_ease_learning

    25/47

    {JFrame frame = new JFrame("My frame");frame.setLayout(null);JButton b1 = new JButton("Button 1");b1.setBounds(0,0,100,25);frame.add(b1);JButton b2 = new JButton("Button 2");b2.setBounds(100,0,100,25);frame.add(b2);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

    }}

    Nh vy l chng ta setLayout(null) cho frame v ln lt setBounds (kch thccng nh v tr) cho 2 button. Vy set kch thc cng nh v tr cho chnh frame thdng 2 phng thc sau:import javax.swing.JFrame;import java.awt.*;

    class Core{public static void main(String args[]){

    JFrame frame = new JFrame("My frame");frame.setLayout(null);JButton b1 = new JButton("Button 1");b1.setBounds(0,0,100,25);frame.add(b1);JButton b2 = new JButton("Button 2");b2.setBounds(100,0,100,25);frame.add(b2);frame.setLocation(200,100);frame.setSize(200,60);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

    }}

    Bi ny y chang bi trn, c khc l gi y v tr im u ca frame c xc nhbng setLocation, Nu khng setLocation, mc nh l (0,0) cn kch thc c xcnh bng setSize. Lu l 200=chiu di 2 ci button cng li cn 60=chiu rngbutton + chiu rng thanh ban u (=35).

    Bi 4 - setLayout khng ph thuc phn gii mn hnh

    Vi cc ng dng nh th cha cn quan tm lm. Vi cc ng dng trung bnh v lnth ng dng "co gin" ty theo phn gii s l li th ln. Ta c th ly phn giihin hnh v ty bin ng dng nh sau:import javax.swing.JFrame;import java.awt.*;

  • 8/7/2019 Java_ease_learning

    26/47

    public class Core{

    public static void main(String[] args){

    Toolkit kit = Toolkit.getDefaultToolkit();Dimension screenSize = kit.getScreenSize();int screenWidth = screenSize.width;int screenHeight = screenSize.height;JFrame frame = new JFrame("My frame");frame.setSize(screenWidth,screenHeight);frame.setResizable(false);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

    }}

    ngi dng khng thay i c size ca mnh, dng frame.setResizable(false)

    Bi 5 - Cc i tng ha c bn ca Java

    * Button

    Button button=new Button("OK");

    add(button);

    hoc add(new Button("OK"));Button sdng ActionListener nghe skin v truyn hnh ng* Label

    Label label=new Label("The sum of values here:");

    Label l nhn

    * Panel

    Panel panel=new Panel();

    Panel l khung cha.

    Bi 6 Checkbox

    Checkbox dng chuyn i trng thi (state) gia yes/no hay true/false. Khi state l

    true th c nh du. C 3 instructor thng dng l:Checkbox() Checkbox(String label) Checkbox(String label,boolean state) vi label hinth nhn cn state l true/false xc lp state cho mt Checkbox ta dng phng thc setState(true) ly state hin hnh ca mt Checkbox ta dng phng thc getState() x l tnh hung ca Checkbox khi n thay i trng thi, ta phi cho n implementsgiao din ItemListener, v bn trong n c phng thc itemStateChanged(ItemEvent

  • 8/7/2019 Java_ease_learning

    27/47

    e). Cn Checkbox thc hin nhng hnh ng ca lp y th ta phi dng phngthc addItemListener.import javax.swing.JFrame;import java.awt.*;import java.awt.event.*;class Core

    {public static void main(String args[]){

    JFrame frame = new JFrame("My frame");Checkbox checkbox=new Checkbox("Documents",false);checkbox.addItemListener(new ItemListener(){

    public void itemStateChanged(ItemEvent e){

    System.out.println("Changed");}

    });frame.add(checkbox);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.pack();frame.setVisible(true);

    }}

    v d ny th mi ln bn thay i trng thi Checkbox, mn hnh Console s in racu "Changed" By gi nu bn mun mn hnh in ra ch khi no n c chn m thi,th sa li phng thc itemStateChanged nh sauif(e.getStateChange()==ItemEvent.SELECTED) System.out.println("Changed");

    SELECTED v DESELECTED l 2 hng s bin din trng thi true hay false ca

    Checkbox

    Bi 7 - Checkbox nhiu ty chn (CheckboxGroup)

    u tin, hy to mt nhm Checkbox nh sau CheckboxGroup g=newCheckboxGroup();Sau a cc Checkbox mun a vo nhm Checkbox nh sauCheckbox c1=new Checkbox("Option 1",g,true);Checkbox c2=new Checkbox("Option 2",g,false);

    Checkbox c2=new Checkbox("Option 2",g,false);C 3 ci cng mang gi tr false cng c, nhng nu l true th ch c mt ci trueBi tp sau s to mt CheckboxGroup c 3 Checkbox. listener bit l Checkbox noc chn, ta dng phng thc getItem (tr v Object) Lu l c 3 Checkboxcng hin th trn frame, ta dng Panelimport javax.swing.JFrame;import java.awt.*;import java.awt.event.*;class Core

  • 8/7/2019 Java_ease_learning

    28/47

    {public static void main(String args[]){

    JFrame frame = new JFrame("My frame");CheckboxGroup g=new CheckboxGroup();Checkbox c1=new Checkbox("Option 1",g,true);Checkbox c2=new Checkbox("Option 2",g,false);Checkbox c3=new Checkbox("Option 3",g,false);MyItemListener listener = new MyItemListener();c1.addItemListener(listener);c2.addItemListener(listener);c3.addItemListener(listener);Panel panel=new Panel();frame.add(panel);panel.add(c1);panel.add(c2);panel.add(c3);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.pack();frame.setVisible(true);

    }}class MyItemListener implements ItemListener{

    public void itemStateChanged(ItemEvent e){

    if(e.getStateChange()==ItemEvent.SELECTED){

    Object temp=e.getItem();String s=(String)temp;System.out.println(s);

    }}

    }

    Lu (String)temp thc ra l ly ci label ca Object temp. 2 lnh c th thay th bng1 lnh String s=(String)e.getItem();

    Bi 8 Choice

    Choice myChoice = new Choice();sau a mc chn vo Choice nhsau

    myChoice.addItem("Red");myChoice.addItem("Green");myChoice.addItem("Blue");Khi 3 mc chn c nh s ln lt l 0,1,2 (t l i: th t mc chn) b mc chn no ra khi Choice, ta dng myChoice.remove(i) vi i l th t mcchn b ttc mc chn khi Choice, ta dng myChoice.removeAll() chn mc chn no trong Choice, ta dng muChoice.select(i)

  • 8/7/2019 Java_ease_learning

    29/47

    Lu l ta c th dng s th t hoc nhn u c, v d myChoice.remove("Blue")hay myChoice.remove(2) u c. V nu c 10 mc chn c nhn l "Blue" thmyChoice.remove("Blue") ch xa mc chn u tin n tm thyimport javax.swing.JFrame;import java.awt.*;import java.awt.event.*;

    class Core{

    public static void main(String args[]){

    JFrame frame = new JFrame("My frame");Choice myChoice = new Choice();myChoice.addItem("Red");myChoice.addItem("Green");myChoice.addItem("Blue");myChoice.addItemListener(new ItemListener(){

    public void itemStateChanged(ItemEvent e){

    if(e.getStateChange()==ItemEvent.SELECTED){String s=(String)e.getItem();System.out.println(s);

    }}

    });frame.add(myChoice);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.pack();frame.setVisible(true);

    }}

    Bi 9 List

    Vi Checkbox, ta ch c thchn gia 2 trng thi true/false ca mt i tng. ViCheckboxGroup v Choice, ta ch c thmt trong cc i tng. Vi List, ta c thchn mtvi i tng, thm ch chn ht.Mc nh ca mt List l ch hin th ti a 4 phn t. Cc phng thc khi to:List() s to mt List mi ln chn ch chn c mt hng (n chn)List(int num) s to mt danh sch mi ln chn mi ln chn ch chn c mt hng, nhngs hin th num hng chkhng phi l 4 nh mc nhList(int num,boolean multiMode) y chang ci trn, nhng thm l mi ln chn c chn nhiuphn tmt lc (nu multiMode l true) (a chn)Nh vy List(7) v List(7,false) l nh nhau, hin th 7 hng mt lc v mi ln chn ch chnc mt hngadd phn tvo List:

  • 8/7/2019 Java_ease_learning

    30/47

    List myList=new List(3,true);

    myList.add("Pascal");

    myList.add("C\\C++");

    myList.add("VB");

    myList.add("Java");

    Cc phn tcng c nh thtt0. thm phn tvo vtr no ta a vo ch stathch, v dmyList.add("Assembler",0);

    thay thmt phn tti vtr no ta dng phng thcmyList.replaceItem("VB.NET",2); //VB b thay bng VB.NETxa mt phn tno ta dng phng thc remove(i)myList.remove(3); hay myList.remove("Java"); u c. V nu c 10 mc chn c nhn l"Java" th myList.remove("Java") ch xa phn tu tin n tm thyxa tt c ta dng myList.removeAll();chn phn tv b chn phn tta dng select(i) v deselect(i)

    Bi 10 - Lm vic vi List

    * Vi List n chn bit c phn t no c chn, ta dng2 phng thc int getSelectedIndex()v String getSelectedItem()int getSelectedIndex() s tr v s th t ca phn t c chn, nu khng cphn t no th tr v -1String getSelectedItem() s tr v label ca phn t c chn, nu khng c phn

    t no th tr v ""final List l=new List();l.add("Pascal");l.add("C\\C++");l.add("VB");l.add("Java");frame.add(l);l.addItemListener(new ItemListener(){

    public void itemStateChanged(ItemEvent e){

    System.out.println(l.getSelectedIndex()+""+l.getSelectedItem());

    }});

    * Vi List a chn bit c nhng phn t no c chn, ta dng 2 phng thc int[]getSelectedIndexs() v String[] getSelectedItems()int[] getSelectedIndexs() l mt mng s tr v nhng s th t ca cc phn t c chn, nu khng c phn t no th tr v -1

  • 8/7/2019 Java_ease_learning

    31/47

    String[] getSelectedItems() l mt mng s tr v nhng label ca cc phn t cchn, nu khng c phn t no th tr v ""final List l=new List(3,true);l.add("Pascal");l.add("C\\C++");l.add("VB");

    l.add("Java");frame.add(l);l.addItemListener(new ItemListener(){

    public void itemStateChanged(ItemEvent e){

    int[] a=l.getSelectedIndexs();String[] b=l.getSelectedItems();for(int i=0;i

  • 8/7/2019 Java_ease_learning

    32/47

    Gi snu bn mun lm ra mt chng trnh bng tnh, dliu nhp vo TextField, by gimun chuyn dliu y ra sthc tnh tons=textField.getText();

    value1=Float.parseFloat(s);

    Tng tvi Byte.parseByte,Integer.parseInt,Double.parseDouble,...

    Bi 12 - Scrollbar (thanh trt)

    Scrollbar c cp nht theo 3 tnh hung unit,block v absolute- Khi ngi dng click chut vo mi tn 2 u Scrollbar th unit ny sinh, thanh trts t ng tr i hay cng thm v tr ca con trt 1 n v (ta c th thay i gi trny, mc nh l 1)- Khi ngi dng click chut vo khong gia thanh trt v v tr hin hnh th blockny sinh, con trt s dch chuyn mt khong l block

    - Khi ngi dng nm vo v tr hin ti cacon trt v li (drag) n t v tr ny sangv tr khc, absolute ny sinh* Khi to thanh trtScrollbar() l n gin nht, mc nh l thanh trt ngScrollbar(int orientation) vi orientation l Scrollbar.HORIZONTAL (ngang) hayScrollbar.VERTICAL (ng)Scrollbar(int orientation,int position,int block,int min,int max) l y nht, v dScrollbar(Scrollbar.HORIZONTAL,50,15,0,100) tc l thanh trt ngang, phm vi t 0n 100, v tr ban u ca con trt l 50 (gia thanh) khi tnh thung block xy ra thcon trt di chuyn 15

    * Cc phng thc ca thanh trt thay i gi tr unit (mc nh l 1) ta dng setUnitIncrement(int unit) vi unit mi thay i gi tr block ta dng setBlockIncrement(int block) vi block mi bit v tr hinhnh ca con trt ta dng int getValue()* Vit b nghe v hnh ng cho thanh trt x l tnh hung ca Scrollbar khi n thay i trng thi, ta phi cho n implementsgiao din AdjustmentListener, v bn trong n c phng thcadjustmentValueChanged(AdjustmentEvent e). Cn Scrollbar thc hin nhng hnhng ca lp y th ta phi dng phng thc addAdjustmentListener.Tuy vy, mt thanh trt th mi khi tc ng n n, n phi "cun" mt ci g y.Mun AdjustmentListener p ng mi khi ta"cun" th cn AdjustmentEvent e bit

    c v tr con trt ang u, ta dng e.getValue(). V d sau l thanh trt vTextFieldimport javax.swing.JFrame;import java.awt.*;import java.awt.event.*;class Core{

    public static void main(String args[]){

  • 8/7/2019 Java_ease_learning

    33/47

    JFrame frame = new JFrame("My frame");Panel p=new Panel();frame.add(p);Scrollbar s=new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,100);p.add(s);final TextField t=new TextField(100);t.setEditable(false);p.add(t);s.addAdjustmentListener(new AdjustmentListener(){

    public void adjustmentValueChanged(AdjustmentEvent e){

    int currentPos=e.getValue();String text="";for(int i=0;i

  • 8/7/2019 Java_ease_learning

    34/47

    import javax.swing.JFrame;import java.awt.*;import java.awt.event.*;class Core{

    public static void main(String args[]){

    //frame khong phu thuoc do phan giai man hinhToolkit kit = Toolkit.getDefaultToolkit();Dimension screenSize = kit.getScreenSize();int screenWidth = screenSize.width;int screenHeight = screenSize.height;int frameWidth = 200;int frameHeight = 60;JFrame frame = new JFrame("My frame");frame.setLayout(null);frame.setLocation((screenWidth-frameWidth)/2,(screenHeight-

    frameHeight)/2);frame.setSize(frameWidth,frameHeight);frame.setResizable(false);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //tao Button Exit cai dat phuong thuc hanh dong qua classrieng

    Button b1 = new Button("Exit");b1.setBounds(0,0,100,25);frame.add(b1);EventQuit eventQuit=new EventQuit();b1.addActionListener(eventQuit);

    //tao Button About cai dat phuong thuc hanh dong truc tiepfinal Button b2 = new Button("About");b2.setBounds(100,0,100,25);frame.add(b2);b2.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e){

    if(e.getSource()==b2) System.out.println("Madein Vietnam");

    }});frame.setVisible(true);

    }}class EventQuit implements ActionListener{

    public void actionPerformed(ActionEvent e){

    System.exit(0);}

    }

  • 8/7/2019 Java_ease_learning

    35/47

    Bi trn dng li cc kin thc hc trc y: setLayout(null) v setBounds, tng dng gia mn hnh v khng ph thuc phn gii mn hnh nh dng Toolkit, 2cch ci t phng thc hnh ng qua class ring v ci t trc tip.

    Bi 15 - To v add hng lot button

    Bn hy c tng tng nu bn phi add khong 30 button vo Frame ca mnh, bnphi vit khong 30 cu lnh khi to, add rt l mt. Hy my t ng lm chobn, ch vi vi vng lp. Bn cn dng mt bng String lu nhng label ca buttonv mt mng Button lu chnh nhng button. ng thi cng da vo mng Buttony ci t phng thc hnh ngimport javax.swing.JFrame;import java.awt.*;import java.awt.event.*;class Core extends JFrame implements ActionListener{

    Panel p=new Panel();final String[]

    a={"File","Edit","View","Insert","Format","Table","Windows","Help"};final Button[] b=new Button[a.length];public Core(String title){

    setTitle(title);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);add(p);setSize(500,60);for(int i=0;i

  • 8/7/2019 Java_ease_learning

    36/47

    Bi 16 - MenuBar,Menu v MenuItem

    * MenuBar v Menu thy c cc Menu nh File, Edit, Help nh trn mt ca s Windows thngthng th tt c cc i tng Menu y phi c add vo mt MenuBar. Menubar

    c th xt hin trong JFrame th ta dng phng thc setMenuBar(menuBar). Chngtrnh sau minh ha mt ng dng nh vyimport javax.swing.JFrame;import java.awt.*;class Core{

    public static void main(String args[]){

    JFrame f = new JFrame("My frame");f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);MenuBar menuBar=new MenuBar();f.setMenuBar(menuBar);Menu file=new Menu("File");

    menuBar.add(file);Menu edit=new Menu("Edit");menuBar.add(edit);Menu help=new Menu("Help");menuBar.setHelpMenu(help);//phan code duoi them vao dayf.setSize(200,60);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

    }}

    * Menu v MenuItem

    Cn New, Open, Save hin ra trong menu File th cc MenuItem y phi c addvo menu File. Ta thm vo nh sauMenuItem newItem=new MenuItem("New");

    file.add(newItem);

    MenuItem openItem=new MenuItem("Open");

    file.add(openItem);

    MenuItem saveItem=new MenuItem("Save");

    file.add(saveItem);

    saveItem.setEnable(false);

    //phan code duoi them vao dayfile.addSeparator(); //phuong thuc nay dua mot hang phan cach vao menu File

    MenuItem exitItem=new MenuItem("Exit");

    file.add(exitItem);

    cho mt MenuItem khng th chn c, ta dng phng thc setEnable(false)(mc nh l true) v d nh trn saveItem.setEnable(false); iu ny c bit hu chvi ng dng vn bn cha c ch no th khng nn cho ngi dng chn MenuItem

  • 8/7/2019 Java_ease_learning

    37/47

    saveItem

    * Menu v submenu

    to mt MenuItem cha mt Menu khc (submenu), ta ch vic to Menu ri addvo menu item kia l xong. Ta thm vo nh sau

    Menu print=new Menu("Setup Print");file.add(print);

    MenuItem previewItem=new MenuItem("Preview");

    print.add(previewItem);

    MenuItem printItem=new MenuItem("Print");

    print.add(printItem);

    //phan code duoi them vao day

    * CheckboxMenuItem

    Bn cng c th to mt mc chn c kh nng nh du bng cch s dng lpCheckboxMenuItem

    CheckboxMenuItem autosave=new CheckboxMenuItem("Auto Save");

    file.add(autosave);

    Ngoi ra cn mt phng thc khi to khc l CheckboxMenuItem autosave=newCheckboxMenuItem("Auto Save",true); Mc nh l false (cha chn)

    Bi 17 - Khi to v ci t phng thc hnh ng hng lot

    Bn hy c tng tng nu bn phi lm mt ng dng ging nh Microsoft Word

    (ch mi ni Word thi ch cha dm ng ti Photoshop, Corel g c) vi mt l Menuv mi Menu c hn chc ci MenuItem. Vy th bn phi khi to, phi add rt l mt.Hy my t ng lm cho bn, ch vi vi vng lp. Bn cn dng mt bng String lu nhng label ca menu v mt mng Menu lu chnh nhng menu.import javax.swing.JFrame;import java.awt.*;import java.awt.event.*;class Core{

    public static void main(String args[]){

    JFrame f = new JFrame("My frame");

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);MenuBar menuBar=new MenuBar();f.setMenuBar(menuBar);final String[]

    menuLabel={"File","Edit","View","Insert","Format","Table","Windows","Help"};final Menu[] menu=new Menu[menuLabel.length];for(int i=0;i

  • 8/7/2019 Java_ease_learning

    38/47

    }final String[] fileMenuItemLabel={"New","Open","Save","Exit"};final MenuItem[] fileMenuItem=new

    MenuItem[fileMenuItemLabel.length];for(int i=0;i

  • 8/7/2019 Java_ease_learning

    39/47

    com.sun.java.swing.plaf.motif.MotifLookAndFeel (giao din UNIX)Sau khi set, giao din hin th trn JFrame no, cn cp nht trn JFrame bngphng thc sauSwingUtilities.updateComponentTreeUI(myFrame) (myFrame l tn JFrame cn cpnht)

    V d sau s minh ha cch thay i LaF da vo CheckboxGroup. Cn ni thm lphng thc UIManager.setLookAndFeel(String className) bt buc phi x l ngoi limport javax.swing.JFrame;import java.awt.*;import java.awt.event.*;class Core{

    public static void main(String args[]){

    final JFrame f = new JFrame("My JFrame");final String[] a={"Metal","Windows","Motif"};final Checkbox[] b=new Checkbox[a.length];final String[] c=new String[a.length];

    CheckboxGroup g=new CheckboxGroup();c[0]="javax.swing.plaf.metal.MetalLookAndFeel";c[1]="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";c[2]="com.sun.java.swing.plaf.motif.MotifLookAndFeel";Panel p=new Panel();f.add(p);for(int i=0;i

  • 8/7/2019 Java_ease_learning

    40/47

    f.setVisible(true);}

    }

    Bi 20 - Cch s dng LaF ca hng th 3:

    Cch 1: coi n nh l 1 add-in plugin, tc l a ci file .jar cha class mnh cn voth mc jdk1.5.0\jre\lib\ext ri c th iu chnh className cho ph hp

    Cch 2: gii nn file .jar ra v tng thng n vo gi jdk1.5.0\jre\lib\rt.jarV d: bn DOWN c gi xplookandfeel.jar v chp n theo cch 1Bn hy m file readme ca gi ny ra v tm thy className ca n l"com.stefankrause.xplookandfeel.XPLookAndFeel" th a thm n vo* LaF c bn quyn ( y ly v d l Alloy-c c m) s dng LaF c bn quyn bn setProperty cho n, v d l dng AlloyLaF(className l "com.incors.plaf.alloy.AlloyLookAndFeel")import javax.swing.*;import java.awt.*;import java.awt.event.*;class Core{

    public static void main(String args[]){

    com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode","v#ej_technologies#uwbjzx#e6pck8");

    final JFrame f = new JFrame("My f");final String[] a={"Metal","Windows","Motif","XP","Alloy"};final Checkbox[] b=new Checkbox[a.length];

    final String[] c=new String[a.length];CheckboxGroup g=new CheckboxGroup();c[0]="javax.swing.plaf.metal.MetalLookAndFeel";c[1]="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";c[2]="com.sun.java.swing.plaf.motif.MotifLookAndFeel";c[3]="com.stefankrause.xplookandfeel.XPLookAndFeel";c[4]="com.incors.plaf.alloy.AlloyLookAndFeel";Panel p=new Panel();f.add(p);for(int i=0;i

  • 8/7/2019 Java_ease_learning

    41/47

    UIManager.setLookAndFeel(c[j]);

    }catch(Exception

    exception){

    System.out.println("LaF not found");}

    SwingUtilities.updateComponentTreeUI(f);}

    }}

    });}f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

    }}

    Bi 21 Jcheckbox

    * JCheckBox tng t Checkboximport javax.swing.*;import java.awt.*;import java.awt.event.*;class Core{

    public static void main(String args[]){

    JFrame frame = new JFrame("My frame");JCheckbox checkbox=new JCheckbox("Documents",false);checkbox.addItemListener(new ItemListener(){

    public void itemStateChanged(ItemEvent e){

    System.out.println("Changed");}

    });frame.add(checkbox);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

    }}

    Bi 22 - JRadioButton v ButtonGroup

    * JRadioButton v ButtonGroup tng t Checkbox v CheckboxGroupimport javax.swing.*;import java.awt.*;import java.awt.event.*;class Core

  • 8/7/2019 Java_ease_learning

    42/47

    {public static void main(String args[]){

    com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode","v#ej_technologies#uwbjzx#e6pck8");

    final JFrame f = new JFrame("My f");final String[] a={"Metal","Windows","Motif","XP","Alloy"};final JRadioButton[] b=new JRadioButton[a.length];final String[] c=new String[a.length];c[0]="javax.swing.plaf.metal.MetalLookAndFeel";c[1]="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";c[2]="com.sun.java.swing.plaf.motif.MotifLookAndFeel";c[3]="com.stefankrause.xplookandfeel.XPLookAndFeel";c[4]="com.incors.plaf.alloy.AlloyLookAndFeel";ButtonGroup g=new ButtonGroup();JPanel p=new JPanel();f.add(p);for(int i=0;i

  • 8/7/2019 Java_ease_learning

    43/47

    Bi 23 - JComboBox v Jlist

    * JComboBox tng t nh Choiceimport javax.swing.*;import java.awt.*;class Core

    {public static void main(String args[]){

    JFrame f = new JFrame("My frame");String[] label={"ASM","C\\C++","VB","Java"};JComboBox box=new JComboBox(label);f.add(box);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setSize(100,55);f.setVisible(true);

    }}

    * JList tng t List nhng n li khng t ko th c nh List, cn c s h tr caJScrollPaneimport javax.swing.*;import java.awt.*;class Core{

    public static void main(String args[]){

    JFrame f = new JFrame("My frame");String[] label={"ASM","Pascal","C\\C++","VB","Java"};JList l=new JList(label);ScrollPane s=new ScrollPane();s.add(l);

    f.add(s);f.setSize(100,100);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

    }}

    * Cn li th JMenuBar,JMenu,JMenuItem tng t MenuBar,Menu,MenuItem

    Bi 24 JtabbedPane

    y gi l i tng phn trang. V d di y minh ha 1 trong cc phng thcaddTab l JTabbedPane.addTab(String title,Component component) Cc componenttrong v d u l cc JButtonimport javax.swing.*;import java.awt.*;class Core{

    public static void main(String args[])

  • 8/7/2019 Java_ease_learning

    44/47

    {JFrame f = new JFrame("My frame");String[] label={"ASM","Pascal","C\\C++","VB","Java"};JButton[] b=new JButton[label.length];JTabbedPane p=new JTabbedPane();for(int i=0;i

  • 8/7/2019 Java_ease_learning

    45/47

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

    }}

    Bi 26 Jtable

    * JTable hin th d liu c snimport javax.swing.*;import java.awt.*;class Core{

    public static void main(String args[]){

    JFrame f = new JFrame("My frame");String[][] dat={{"1","JCreator","Xinox","Beginer"},

    {"2","jGRASP","Auburn","Medium"},

    {"3","NetBeans","SunMicrosystems","Expert"},

    {"4","Gel","GExperts","Beginer"},

    {"5","Eclipse","Eclipse","Expert"},

    {"6","JBuilder","Borland","Expert"}};String[] columnName={"ID","Name","Company","Rank"};JTable t=new JTable(dat,columnName);JScrollPane s=new JScrollPane(t);f.add(s);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setSize(400,100);f.setVisible(true);

    }}

    * Thao tc trc tip d liu trong tng ca bngTrong v d di chng ta s thay i d liu ca ct "Rank" bng mt JComboBox, sdng class TableColumnimport javax.swing.*;import java.awt.*;import javax.swing.table.*;class Core{

    public static void main(String args[]){

    JFrame f = new JFrame("My frame");String[][] dat={{"1","JCreator","Xinox","Beginer"},

    {"2","jGRASP","Auburn","Medium"},{"3","NetBeans","Sun

    Microsystems","Expert"},

    {"4","Gel","GExperts","Beginer"},

  • 8/7/2019 Java_ease_learning

    46/47

    {"5","Eclipse","Eclipse","Expert"},

    {"6","JBuilder","Borland","Expert"}};String[] columnName={"ID","Name","Company","Rank"};JTable t=new JTable(dat,columnName);JScrollPane s=new JScrollPane(t);f.add(s);JComboBox c=new JComboBox(new

    String[]{"Low","High","Extremely"});TableColumn rankColumn=t.getColumn("Rank");rankColumn.setCellEditor(new DefaultCellEditor(c));f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setSize(400,100);f.setVisible(true);

    }}

    Bi 27 - JOptionPane c bn

    y c th ni l cng c Dialog mnh nhtTrc tin hy xem qua v d sauimport javax.swing.*;class Core{

    public static void main(String args[]){

    JFrame f = new JFrame("My frame");JOptionPane.showMessageDialog(f,"Hien thi cau thong bao","Hien

    thi tieu de",JOptionPane.ERROR_MESSAGE);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    f.setVisible(true);}}

    JOptionPane bao gm cc thnh phn chnh sau y: Title, Icon, Message, InputValuev OptionButtons. Khng cn bao gm tt c* Khi to ca JOptionPaneJOptionPane(Object message, int messageType, int optionType, Icon icon, Object[]options)Bn c th thu bt c thnh phn no thm ch c th thiu htObject message: cu thng bo hin th trn JOptionpane

    int messageType: bao gm ERROR_MESSAGE, INFORMATION_MESSAGE,WARNING_MESSAGE, QUESTION_MESSAGE, v PLAIN_MESSAGEint optionType: bao gm DEFAULT_OPTION, YES_NO_OPTION,YES_NO_CANCEL_OPTION, OK_CANCEL_OPTIONIcon icon: hnh icon ca JOptionPane

    V d:

  • 8/7/2019 Java_ease_learning

    47/47

    import javax.swing.*;class Core{

    public static void main(String args[]){

    JFrame f = new JFrame("My frame");f.add(new JOptionPane("Hien thi cau thong bao",

    JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION));f.setSize(250,150);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);

    }}

    * Cc phng thc (hay s dng hn)void showMessageDialog(Component parentComponent, Object message, String title,

    int messageType)

    String showInputDialog(Component parentComponent, Object message, String title, int

    messageType)int showConfirmDialog(Component parentComponent, Object message, String title, int

    optionType, int messageType) Yes tr v 0 v No tr v 1