Java Ease Learning (ThucHanh)

You might also like

You are on page 1of 47

CHNG I - BT U VI JAVA

Bi 1 Hello world
Bn hy xem bi ca anh CEO trong JVN

Bi 2 In ra chui nhp vo
Bi 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 ti chng 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 t
thi.

*L thuyt: cu trc mt chng trnh Java
public class Core {
public static void main(String[] args) {
System.out.println("Hello,Everybody in the World!");
}
}

public class Core bn bt u mt lp Java
public static void main(String[] args) y l mt phng thc main trong Java, cho
chng trnh chy c. Tm thi bn phi g y nh th ny
System.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));
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 dng
String str khai bo bin str kiu chui, v
System.out.println("Welcome " + str + " to Java")
y cng l dng System.out.println nh chng trnh u, c khc l + str + tc l
a mt bin vo chui in ra. Ch n thi nh, sau , hy quan tm n bi hm
nay
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);

*Gii thch
import bn nhp class hay th vin chun, tm thi ng quan tm n l g, ch cn
nh l c n chng trnh chy
System.out.print in ra mt chui, nhng khng xung dng
System.out.println in ra mt chui, nhng xung dng
int ketqua tc l khai bo bin ketqua kiu int
ketqua = a+b tc l gn kt qu mt biu thc tnh ton ( y l bin a + bin b) cho
bin ketqua
System.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 d
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());
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 2
Php chia s l php chia ht nu c 2 ton hng u kiu nguyn, gi l chia ly
nguyn (/) hay div




By gi cng chng trnh y m ta thay i li cht xu xem sao
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 1
y l kt qu php chia ly 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 chia
ly nguyn th sao ? Trong trng hp , bn dng p kiu
int a=5,b=2;float ket qua;
ketqua=(float)a/b;

Bi 5 Lp trnh OOP
Bn xem bi ca anh CEO trong JVN
class
y l mt class, class ny c hai property (thuc tnh) l name v age
public 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 bn
thn ci class ( y l class Person).
Trong class Person c mt property l age, cu this.age = age c ngha l ci thuc tnh
age ca class Person s nhn gi tr ci i s age do constructor Person(int age) a
vo.
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 sau
Person 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 k
tha
-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 c
php 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 tuong
String hoten;
int age;
String diachi;
int luong;
//cac constructor
public Person(int age)
{
this.age = age;
}
//cac method hay behavior-hanh vi cua doi tuong
public 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 no
them 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::");
}
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 tnh
Tt c cc i tng th hin t lp cha u c php thay i gi tr ca cc thuc
tnh khng tnh,cn gi tr ca thuc tnh tnh th khng c php thay i
public class Car
{
public string branch;
public int cost;
public static int tire=4;
}

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

Khai bo mt hnh vi
Mt phng thc c khai bo nh sau
public 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) v
volatile (linh hot), static(tnh)

-nu khng khai bo,mc nh l khng tnh
class 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 thc
TestObject test=new TestObject();
test.NonStaticMethod();
Nu l mt phng thc tnh,bn c php gi trc tip t lp
TestObject.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 vi
ln v vy khng ghi vo thanh ghi

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 ca
giao din l final cn behavior l abstract
Gi s, ta s khai bo mt giao din
public interface Product
{
//hai state duoi day la final, tuc la lop implements khong duoc phep
doi gia tri
static string maker = My Corp;
static string phone = 555-7767;
//behavior duoi day la abstract, tuc la khong co noi dung
public int getPrice(int id);
}

By gi, ta s vit mt class c ci t (implements) giao din ny
public 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 Car
implements ActionCar, ActionMobilation

package-unit
Hy to 1 th mc c tn l Transport
Bn 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)
{
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 vn
c th khai bo tng minh nh sau
Transport.Car myCar = new Transport.Car();

np chng (overload) 1 phng thc
class 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 khc
tham 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, c
cng mt tn nhng danh sch i s khc nhau
Phng thc c ghi l phng thc c mt lp cha, c xc nh l phng
thc chung cho cc lp con, ri xut hin cc lp con
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 d liu nguyn thy v php ton

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

Hng k t khai bo nh sau, v d 'H' (khc vi "H" l mt chui k t)
Mt s hng k t c 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 boolean
C 2 gi tr l 2 t kha true v false, v khng th chuyn kiu sang int

*Khai bo bin
int i,j; //2 bin i v j c kiu d liu l int
char ch='A'; //bin ch kiu char khi to gi tr u 'A'

*Khai bo hng
Hng c khai bo vi t kha final. V d:
final float PI = 3.14159;

*Php ton
Php ton ca Java ging C. Trong class java.lang.Math c mt s method dng trong ton
hc nh sau
double y = Math.pow(x,a) = x
v random, sin, cos, tan, exp (m), log(logarit) ...

* Cc php ton s hc
- Vi c kiu nguyn v kiu thc: + - * / (php chia s cho ra kt qu kiu thc nu mt trong
2 ton t l kiu thc)
- Chia ht (/) ch p dng khi c 2 ton t l kiu nguyn, v d 10/3=3
- Chia ly d (%) ch p dng khi c 2 ton t l 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-- S khc nhau ch l
khi 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 ton
khc
- Vi bin++ v bin-- th n s thc hin php ton khc trc ri mi thc hin php ton
ny

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

* Trnh t kt hp
Hu ht cc php ton iu c trnh t kt hp t tri sang phi, ch c cc php sau l t phi
sang tri
- Php ++ v --
- Cc php gn nh =,+=,-=,<<=,>>=

Bi 7 Mnh if

nu em p th ti s ca em khng th ti ca a khc
IF 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 l
if(mnh ) lnh 1;
else lnh 2;
Nu mnh ng th thc hin lnh 1;
Khng th thc hin lnh 2;

V d
if(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 s
Nhp vo mt s bt k. Nu phn thp phn s ny >=0.5, lm trn tng ln mt n
v, 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 if
if(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 th
a=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 gii
phng trnh bc mt v hai, ngoi ra cn nhiu bi tp khc na. y ch c gii
phng trnh bc mt. Bn nn tm nhiu bi tp t lm trc khi tip tc phn k.

V d: phng trnh bc 1
import 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 so
nghiem");
if(b!=0) System.out.println("Phuong trinh vo dinh");
}
else System.out.println("Phuong trinh mot nghiem x=" + -b/a);
}
}


Bi 8 switch

Bn hc xong if. Bn mun dng vng lp if nh gi im s nhp vo. Bn s
vit chng trnh sau y
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 diem so: ");
int diem = Integer.parseInt(in.readLine());
if(diem<=2) System.out.println("Yeu");
if((diem>2) && (diem<=3)) System.out.println("Trung binh");
if((diem>3) && (diem<=4)) System.out.println("Kha");
if((diem>4) && (diem<5)) System.out.println("Gioi");
if(diem==5) System.out.println("Xuat sac");
}
}

Thay v lp li nhng cu if y, bn nn dng switch
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 diem so: ");
int diem = Integer.parseInt(in.readLine());
switch(diem)
{
case 0:
case 1:
case 2:System.out.println("Yeu");break;
case 3:System.out.println("Trung binh");break;
case 4:
case 5:System.out.println("Gioi");break;
default:System.out.println("Vao sai");
}
}
}

*break vi switch: break s thot ngay ra khi khi lnh trong thn ca switch

Bi 9 String

Khc vi C, String l mt lp ca Java. String c khai bo nh sau
String a = "Hello";
Cng 2 String bng du +
System.out.println("Gia tri la " + n);
Java c kh nng t chuyn kiu bt c d liu kiu s no khi cng vo String. D n l int,
float, double u c th chuyn thnh String nh mo vt ("" + n)

Cc method trong class String
* substring
String s1 = "Hello";
String s2 = s1.substring(0,4); //bt u t k t th 0 (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 t th i trong String, cc k t trong String c nh s t 0

* equals
Kiu tra xem chui ngun s c ging chui ch d hay khng, ta dng method equals tr v
boolean
boolean b = s.equals(t);
String khng ging d liu kiu s, tuyt i khng dng ging nh if(s==t)

* compareTo
int a = s2.compareTo(s1);
a>0 s2>s1
a<0 s2<s1
a=0 s2=s1
So snh gia s2 v s1 l so snh th t gia k t u ca hai chui so i, v d "kc" > "kazbe"

* toCharArray (i chui ra mng k t)
char[] chuoi = s1.toCharArray();

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

* Chuyn kiu t String ra d liu kiu s
Chuyn t d liu kiu s ra String kh d dng, dng "" + n, nhng ngc li th phi dng
cc 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 230
Tng t vi cc method sau Byte.parseByte, Short.parseShort, Float.parseFloat, ...

Bi 10 vng lp for

for(int i=0;i<n;i++)
s+=i;
3 thnh phn trong cu for ta c th b ht nhng phi gi li cc du ; khi nn
mun ta c th t php ton iu khin vng lp trong thn lnh nh sau
for(int i=0;i<n;)
{
s+=i;
i++;
}

*break vi for: break s thot ngay ra khi vng for
for(int i=0;i<n;i++)
{
System.out.println(i);break;
System.out.println("Tiep tuc");
}

Kt qu in ra khng c cu "Tiep tuc" v break nhy ngay ra khi vng for sau khi in 1
*continue vi for: continue s khin vng for bt u 1 chu trnh mi v b qua tt c
cc lnh bn di n

VD: in tt c cc s t 0 n 10, b qua 3,4,5
for(int i=0;i<10;i++)
{
if((i= =3)||(i= =4)||(i= =5)) continue;
System.out.println(i);
}


Bi 11 while
while(biu thc)
lnh;
Nu biu thc ng th thc hin lnh
*break vi while: break s thot ngay ra khi vng while
int i=0;
while(i<10)
{
System.out.println(i);break;
i++;
}

S ch in ra 0
* continue vi while: n s xc nh gi tr biu thc vit ngay sau while
int i=0;
while(i<10)
{
System.out.println(i);continue;
i++;
}

Ta s c mt lot in 0 v tn
Bi 12 vng lp do..while
do
lnh;
while(biu thc);

Nu biu thc ng th tip tc thc hin lnh
*break vi do..while: break s thot ngay ra khi vng while
int i=0;
do
{
System.out.println(i);break;
i++;
}

while(i<10);
S ch in ra 0
* continue vi while: n s xc nh gi tr biu thc vit ngay sau
while
int i=0;
do
{
System.out.println(i);continue;
i++;
}
while(i<10);

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 s phn t
int[] a;
Tuy vy, vi Java, dng c mt array, ta cn phi khi to array , v lc ny phi cung
cp s phn t
int[] a;
a = new int[100];
Hai cu c th vit li thnh mt cu
int[] a = new int[100];
Java s khi to mt mng 100 phn t u l int c nh th t t 0 n 99
Mng c gi tr u: Mng loi ny khng cn new m cng chng cn s phn t
int[] a = {1,45,6,8,21};

Cc method vi mng
* length
method ny s cung cp s phn t ca mng, v d ta mun gn gi tr s cho cc phn t
ca mng a
for(int i=0;i<a.length;i++) a|i|=i; lu l length, khng phi length()

*System.arraycopy
Gi s, ban u ta c 2 mng
int[] s = {1,3,5,7,9,11,13,15};
int[] d = {2,4,6,8,10,12,14};
method arraycopy trong gi System
System.methodcopy(s,3,d,2,4);
s cho ra mt mng d mi l {2,4,7,9,11,13,14}
method ny s thay th 4 phn t, tnh t phn t th 2 trong mng d, bng ngn y phn t
tnh t phn t th 3 trong mng s

Cc method nm trong class java.util.Arrays
* void sort
N s sp xp mt mng s tng dn
int[] s = {28,7,14,11};
Arrays.sort(s);

* int binarySearch
N s tm v tr ca mt phn t trong 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 chiu
int[][] = new int[100][50];
Hoc khai bo 1 mng c gi tr u. y l mng 2 chiu gm 4 phn t l 4 mng 1 chiu,
mi mng 1 chiu cha 3 phn t
int[][] a =
{
{16, 3, 2},
{5, 10, 11},
{9, 6, 7},
{4, 15, 14}
};

Bi 14 - ngoi l
int x,y;
x=10;y=x-10;
x=x/y;
Khi chy on m ny bn s thy xut hin thng bo
java.lang.ArithmeticException: divide by zero
V chng trnh s thot ra ngay lc . Mun chng trnh chy tip v khng thot
ra, ta n "bt" ngoi l ny, a ra bin e, cui cng 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 th
khai bo nm b ngoi l
public void divide() throws Exception
{
int a=5/0;
}
hoc nu mun "bt" ngoi l li xem l ngoi l g x l, bn "bt" n ri
in ra
try
{
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 sinh
thng bo ngoi l, bn c th dng
boolean 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 s phn t)

Cc method trong bi ny nm 2 class java.util.Vector v java.util.Enumeration
Khai bo
Vector vt = new Vector();
Nhp d liu cho mt Vector (class Console nm trong gi corejava)
Lu l mi phn t ca Vector u phi l mt i tng, nn ta phi c new Integer(n) khi
mun a vo mt bin kiu int. Tng t vi 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<vt.size();i++)
System.out.println(vt.elementAt(i));

a Vector v kiu mng cho d thao tc, ta a v kiu Enumeration (mt kiu mng)
Enumeration e = vt.elements();
Nh vy ta c mng e kiu Enumeration sao chp y khun Vector vt d x l, khng ng
n Vector vt
In ra cc phn t ca mt Enumeration
while(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 12kg
System.out.print(a.Weight());
}
}

y ta thy lp ni Apple trong lp TestProgram, khi bin dch Java s lm xut hin
2 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 cha
Lu l lp ni khc vi cc lp m nm chung mt file, v d nh tp tin
MainClass.java di y
public class MainClass
{
}
class Subclass
{
}

Bi 17 - To tp tin jar t chy

Gi s chng trnh ca bn c vi file .class trong file chng trnh chnh l MainPro.class
chng hn.
Bn hy to mt file ly tn l mymf.mf c ni dung nh sau
Main-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 c
mymf.mf vo , ri chy jar.exe vi tham s dng lnh nh sau
jar cmfv mymf.mf MyProgram.jar *.class
Tng t nu bn mun a thm 2 th mc dir1 v dir2 v file JAR th bn cng g
jar cmfv mymf.mf MyProgram.jar *.class dir1 dir2
Trnh jar s to file MyProgram.jar (tn khc ty bn) c th chy c, khng phi dng lnh
java hay gi s khng 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 dng
hn. 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 nht
import javax.swing.JFrame;
class HelloWorldSwing
{
public static void main(String[] a)
{
JFrame frame=new JFrame("Main Frame");//Main Frame la ten cai
cua so
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//ham
dong cua so lai
JLabel label=new JLabel("Hello Everybody, label contain
context");//mot doi tuong do hoa
frame.getContentPane().add(label);//dua doi tuong do hoa vao
trong frame
frame.pack();//"dong goi" lai toan bo trinh do hoa
frame.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 chng
trnh
import javax.swing.JFrame;
import java.awt.*;
class Execute extends JFrame
{
Container container = getContentPane();
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 Vit
Gi s bn mun nt bm ca bn c dng "Vit Nam" v bn khng bit in nh th
no, chng trnh sau s gip bn
JButton 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 tr
trong 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 s
kin tng ng.
Trong v d di y ta c class EventQuit l mt b nghe, b nghe ny thc hin
phng thc actionPerformed chnh l cha nhng s kin ca b nghe . i tng
eventQuit 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[])
{
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 sau
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");
final JButton button = new JButton("My button");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button) System.exit(0); //nu
event 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 i
tng 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 t
trn xung di
Phng thc ny s to ra mt hnh ch nht o bao quanh i tng b add, hnh ch
nht 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[])
{
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 thc
cng nh v tr) cho 2 button. Vy set kch thc cng nh v tr cho chnh frame th
dng 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 nh
bng setLocation, Nu khng setLocation, mc nh l (0,0) cn kch thc c xc
nh bng setSize. Lu l 200=chiu di 2 ci button cng li cn 60=chiu rng
button + 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 ln
th ng dng "co gin" ty theo phn gii s l li th ln. Ta c th ly phn gii
hin hnh v ty bin ng dng nh sau:
import javax.swing.JFrame;
import java.awt.*;
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 s dng ActionListener nghe s kin 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 hin
th 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 implements
giao din ItemListener, v bn trong n c phng thc itemStateChanged(ItemEvent
e). Cn Checkbox thc hin nhng hnh ng ca lp y th ta phi dng phng
thc 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 ra
cu "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 sau
if(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=new
CheckboxGroup();
Sau a cc Checkbox mun a vo nhm Checkbox nh sau
Checkbox 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 true
Bi tp sau s to mt CheckboxGroup c 3 Checkbox. listener bit l Checkbox no
c chn, ta dng phng thc getItem (tr v Object) Lu l c 3 Checkbox
cng hin th trn frame, ta dng Panel
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");
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 bng
1 lnh String s=(String)e.getItem();

Bi 8 Choice

Choice myChoice = new Choice();
sau a mc chn vo Choice nh sau
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 mc
chn
b tt c mc chn khi Choice, ta dng myChoice.removeAll()
chn mc chn no trong Choice, ta dng muChoice.select(i)
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" th
myChoice.remove("Blue") ch xa mc chn u tin n tm thy
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");
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 th chn gia 2 trng thi true/false ca mt i tng. Vi
CheckboxGroup v Choice, ta ch c th mt trong cc i tng. Vi List, ta c th chn mt
vi 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, nhng
s hin th num hng ch khng phi l 4 nh mc nh
List(int num,boolean multiMode) y chang ci trn, nhng thm l mi ln chn c chn nhiu
phn t mt 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 chn
c mt hng
add phn t vo List:
List myList=new List(3,true);
myList.add("Pascal");
myList.add("C\\C++");
myList.add("VB");
myList.add("Java");
Cc phn t cng c nh th t t 0. thm phn t vo v tr no ta a vo ch s ta
thch, v d
myList.add("Assembler",0);
thay th mt phn t ti v tr no ta dng phng thc
myList.replaceItem("VB.NET",2); //VB b thay bng VB.NET
xa mt phn t no 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 t u tin n tm thy
xa tt c ta dng myList.removeAll();
chn phn t v b chn phn t ta dng select(i) v deselect(i)

Bi 10 - Lm vic vi List

* Vi List n chn
bit c phn t no c chn, ta dng 2 phng thc int getSelectedIndex()
v String getSelectedItem()
int getSelectedIndex() s tr v s th t ca phn t c chn, nu khng c
phn t no th tr v -1
String 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
String[] getSelectedItems() l mt mng s tr v nhng label ca cc phn t c
chn, 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<a.length;i++)
System.out.println(a|i|);
for(int j=0;j<b.length;j++)
System.out.println(b[j]);
}
});

Bi 11 - TextField v TextArea

* TextField
C 4 phng thc khi to
TextField() khng thm g c
TextField(String s) vi s l chui ban u xut hin trn TextField (v d "Input your name
here")
TextField(int num) vi num l di TextField
TextField(String s,int num) vi s l chui ban u xut hin trn TextField v num l di
TextField
* TextArea
C 4 phng thc khi to
TextArea() khng thm g c
TextArea(String s) vi s l chui ban u xut hin trn TextArea
TextArea(int row,int column) vi row v column l s hng v ct trn TextField
TextField(String s,int row,int column) l y nht kt hp 2 phng thc khi to trn
* Cc phng thc ca TextField v TextArea
a ni dung vn bn vo bng void setText(String txt)
Ly ni dung vn bn ra bng String getText()
Ly ni dung vn bn ang c nh du (bi en) ra bng String getSelectedText()
ngi dng khng th thay i ni dung bng void setEditable(false) (mc nh l true)
c bit l TextField c mt phng thc m TextArea khng c, l void setEchoChar(char
c). V d setEchoChar('*') th phng thc ny s khin cho tt c k t nhp vo TextField u
ch hin th l k t '*' (rt hu dng khi nhp password)
* Phng thc dng chung vi TextField
Gi s nu bn mun lm ra mt chng trnh bng tnh, d liu nhp vo TextField, by gi
mun chuyn d liu y ra s thc tnh ton
s=textField.getText();
value1=Float.parseFloat(s);
Tng t vi 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 trt
s t ng tr i hay cng thm v tr ca con trt 1 n v (ta c th thay i gi tr
ny, mc nh l 1)
- Khi ngi dng click chut vo khong gia thanh trt v v tr hin hnh th block
ny sinh, con trt s dch chuyn mt khong l block
- Khi ngi dng nm vo v tr hin ti ca con trt v li (drag) n t v tr ny sang
v tr khc, absolute ny sinh
* Khi to thanh trt
Scrollbar() l n gin nht, mc nh l thanh trt ng
Scrollbar(int orientation) vi orientation l Scrollbar.HORIZONTAL (ngang) hay
Scrollbar.VERTICAL (ng)
Scrollbar(int orientation,int position,int block,int min,int max) l y nht, v d
Scrollbar(Scrollbar.HORIZONTAL,50,15,0,100) tc l thanh trt ngang, phm vi t 0
n 100, v tr ban u ca con trt l 50 (gia thanh) khi tnh thung block xy ra th
con 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 hin hnh 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 implements
giao din AdjustmentListener, v bn trong n c phng thc
adjustmentValueChanged(AdjustmentEvent e). Cn Scrollbar thc hin nhng hnh
ng 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 v
TextField
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");
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<currentPos;i++) text+='*';
t.setText(text);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

By gi th mi ln bn ko con trt th k t '*' ly thay i trong TextField t.

Bi 13 - Cc i tng khung cha (container) v b qun l trnh by (layout
manager)

Khung cha ni nm na l nhng ci khung tranh bn cn dn nhng nt v (i tng
ha) ca bn ln . V sp xp cc i tng ny trn khung cha th ca cn ti b qun l
trnh by.
- Khung cha m bn quen thuc l Frame. N ging nh ca s ca Windows v cha ton
b ng dng ca bn
- Mt khung cha khc m bn bit qua l Panel. N ging nh mt ci bng hin thi y
cc thnh phn GUI m bn mun tng ln Frame
- Nhng ci cn li s hc sau. Tt c cc lp Frame,Panel,... u l con ca lp Container
* Cc phng thc ca Container (cc phng thc chung ca cc i tng khung cha)
Component add(Component c) a mt i tng c vo khung cha. V d frame.add(panel);
void remove(Component c) a mt i tng c ra khi khung cha. V d
frame.remove(panel);

Bi 14 - Nhc li v Jframe

Phn 1 ni v JFrame, by gi ch nhc li
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 hinh
Toolkit 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 class
rieng
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 tiep
final 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("Made
in Vietnam");
}
});
frame.setVisible(true);
}
}
class EventQuit implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}

Bi trn dng li cc kin thc hc trc y: setLayout(null) v setBounds, t
ng dng gia mn hnh v khng ph thuc phn gii mn hnh nh dng Toolkit, 2
cch 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, bn
phi vit khong 30 cu lnh khi to, 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 button
v mt mng Button lu chnh nhng button. ng thi cng da vo mng Button
y ci t phng thc hnh ng
import 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<a.length;i++)
{
b|i|=new Button(a|i|);
p.add(b|i|);
b|i|.addActionListener(this);
}
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
for(int i=0;i<a.length;i++)
if(e.getSource()==b|i|) System.out.println("You have
clicked button "+a|i|);
}
public static void main(String args[])
{
Core c=new Core("My frame");
}
}

S d trong bi ny ta dng khi to ca Core l s dng addActionListener(this);

Bi 16 - MenuBar,Menu v MenuItem

* MenuBar v Menu
thy c cc Menu nh File, Edit, Help nh trn mt ca s Windows thng
thng 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). Chng
trnh sau minh ha mt ng dng nh vy
import 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 day
f.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 add
vo menu File. Ta thm vo nh sau
MenuItem 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 day
file.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 ch
vi ng dng vn bn cha c ch no th khng nn cho ngi dng chn MenuItem
saveItem
* Menu v submenu
to mt MenuItem cha mt Menu khc (submenu), ta ch vic to Menu ri add
vo 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 lp
CheckboxMenuItem
CheckboxMenuItem autosave=new CheckboxMenuItem("Auto Save");
file.add(autosave);
Ngoi ra cn mt phng thc khi to khc l CheckboxMenuItem autosave=new
CheckboxMenuItem("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 Menu
v 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<menuLabel.length;i++)
{
menu|i|=new Menu(menuLabel|i|);
menuBar.add(menu|i|);
}
final String[] fileMenuItemLabel={"New","Open","Save","Exit"};
final MenuItem[] fileMenuItem=new
MenuItem[fileMenuItemLabel.length];
for(int i=0;i<fileMenuItemLabel.length;i++)
{
fileMenuItem|i|=new MenuItem(fileMenuItemLabel|i|);
menu[0].add(fileMenuItem|i|);
if(i==2) menu[0].addSeparator();
}
fileMenuItem[3].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
f.setSize(400,60);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}

Bi 18 ScrollPane

import 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);
ScrollPane s=new ScrollPane();
TextArea t=new TextArea();
s.add(t);
f.add(s);
f.setSize(200,120);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}

Bi 19 - LookAndFeel (cm quan giao din)

LookAndFeel (vit tt l LaF gi l cm quan giao din cho ng dng. S dng rt n
gin
UIManager.setLookAndFeel(String className) vi UIManager l mt class cn
className l tn class cha ci LaF . Java h tr sn 3 ci l:
javax.swing.plaf.metal.MetalLookAndFeel (giao din Java)
com.sun.java.swing.plaf.windows.WindowsLookAndFeel (giao din Windows)
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 bng
phng thc sau
SwingUtilities.updateComponentTreeUI(myFrame) (myFrame l tn JFrame cn cp
nht)
V d sau s minh ha cch thay i LaF da vo CheckboxGroup. Cn ni thm l
phng thc UIManager.setLookAndFeel(String className) bt buc phi x l ngoi l
import 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<a.length;i++)
{
b|i|=new Checkbox(a|i|,g,false);
p.add(b|i|);
b|i|.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
for(int j=0;j<a.length;j++)
{
if(e.getSource()==b[j])
{
try
{

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 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 vo
th 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.jar
V d: bn DOWN c gi xplookandfeel.jar v chp n theo cch 1
Bn 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<a.length;i++)
{
b|i|=new Checkbox(a|i|,g,false);
p.add(b|i|);
b|i|.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
for(int j=0;j<a.length;j++)
{
if(e.getSource()==b[j])
{
try
{

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 Checkbox
import 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 CheckboxGroup
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 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<a.length;i++)
{
b|i|=new JRadioButton(a|i|);
g.add(b|i|);
p.add(b|i|);
b|i|.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
for(int j=0;j<a.length;j++)
{
if(e.getSource()==b[j])
{
try
{

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 23 - JComboBox v Jlist

* JComboBox tng t nh Choice
import 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 ca
JScrollPane
import 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 thc
addTab l JTabbedPane.addTab(String title,Component component) Cc component
trong v d u l cc JButton
import 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"};
JButton[] b=new JButton[label.length];
JTabbedPane p=new JTabbedPane();
for(int i=0;i<label.length;i++)
{
b|i|=new JButton(label|i|);
p.addTab(label|i|,b|i|);
}
f.add(p);
f.setSize(300,100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}

Thng thng th cc componenet u l cc khung cha (v d nh JPanel) cha
nhiu i tng ring bit

Bi 25 JtoolBar

JToolBar (thanh cng c) ging y nh bn thng thy trong cc ng dng Windows.
N bao gm nhiu JButton, mi JButton c mt Icon ring. Trc ht hy chun b vi
hnh .gif 24x24 cho v d ny. Nu khng tm thy th chp t
jdk1.5.0\demo\plugin\jfc\Stylepad\resources. Chp vo th mc cha m ngun
import javax.swing.*;
import java.awt.*;
class Core
{
public static void main(String args[])
{
JFrame f = new JFrame("My frame");
JToolBar t=new JToolBar();
String[]
label={"New","Open","Save","Cut","Copy","Paste","Bold","Italic","Underline","
Left","Right","Center"};
String[]
file={"new.gif","open.gif","save.gif","cut.gif","copy.gif","paste.gif","bold.
gif","italic.gif","underline.gif","left.gif","right.gif","center.gif"};
ImageIcon[] icon=new ImageIcon[label.length];
JButton[] b=new JButton[label.length];
for(int i=0;i<label.length;i++)
{
icon|i|=new ImageIcon(file|i|);
b|i|=new JButton(icon|i|);
b|i|.setToolTipText(label|i|);
t.add(b|i|);
if((i==2)||(i==5)||(i==8)) t.addSeparator();
}
f.add(t);
f.setSize(600,70);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}

Bi 26 Jtable

* JTable hin th d liu c sn
import 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","Sun
Microsystems","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 bng
Trong v d di chng ta s thay i d liu ca ct "Rank" bng mt JComboBox, s
dng class TableColumn
import 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"},

{"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 nht
Trc tin hy xem qua v d sau
import 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, InputValue
v OptionButtons. Khng cn bao gm tt c
* Khi to ca JOptionPane
JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[]
options)
Bn c th thu bt c thnh phn no thm ch c th thiu ht
Object message: cu thng bo hin th trn JOptionpane
int messageType: bao gm ERROR_MESSAGE, INFORMATION_MESSAGE,
WARNING_MESSAGE, QUESTION_MESSAGE, v PLAIN_MESSAGE
int optionType: bao gm DEFAULT_OPTION, YES_NO_OPTION,
YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION
Icon icon: hnh icon ca JOptionPane

V d:
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

You might also like