You are on page 1of 55

GVHD: Ths.

Mai Vn H

Thc hnh Lp Trnh Java

CHNG 1 :
CC KIN THC C BN CU TRC CHNG TRNH JAVA

A. CU TRC LA CHN.
1.
2.
3.
4.

Gii phng trnh bc nht : ax+b=0


Phng trnh bc hai : ax2 + bx + c=0
Tm s trung gian ca 3 s a,b,c
Vit chng trnh tnh tin cho bi ton KaraOke
+ Gi bt u : a (int)
+ Gi kt thc : b (int)
+ Nu nh hn 18h : 45000/1h, ln hn 18h : 60000/1h

5. Nhp vo thng, nm bt k. In ra s ngy tng ng vi thng, nm .


Code
import java.util.Scanner;

public class bai1 {


private void giaipt1(){
float a,b;
Scanner keyb = new Scanner(System.in);
System.out.print("a= ");
a= keyb.nextFloat();
System.out.print("b= ");
b= keyb.nextFloat();
if(a==0){
if(b==0) System.out.println("Phuong trinh vo so
nghiem!");
else System.out.println("Phuong trinh vo nghiem!");
}else System.out.println("Phuong trinh co nghiem x= " + (b/a));
}
private void giaipt2(){
float a,b,c;
Scanner keyb = new Scanner(System.in);
System.out.print("a= ");
a= keyb.nextFloat();
SVTH: Nguyn Vn Ph Nhm 12A

Trang 1

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

System.out.print("b= ");
b= keyb.nextFloat();
System.out.print("c= ");
c= keyb.nextFloat();
if(a==0){
if(b==0){
if(c==0) System.out.println("Phuong trinh vo so
nghiem!");
else System.out.println("Phuong trinh vo
nghiem!");
}else System.out.println("Phuong trinh co nghiem x= "
+ (-c/b));
}else{
float denta = b*b-4*a*c;
if(denta < 0) System.out.println("Phuong trinh vo
nghiem!");
else if (denta == 0) System.out.println("Phuong trinh
co nghiem kep x= " + (-b/(2*a)) );
else{
float x1= (float) (-b + Math.sqrt(denta)/(2*a));
float x2= (float) (-b - Math.sqrt(denta)/(2*a));
System.out.println("phuong trinh co 2 nghiem
la: ");
System.out.println("x1= " + x1);
System.out.println("x2= " + x2);
}
}
}
private void trunggian(){
float a,b,c,ok,min,max;
Scanner keyb = new Scanner(System.in);
System.out.print("a= ");
a= keyb.nextFloat();
System.out.print("b= ");
b= keyb.nextFloat();
System.out.print("c= ");
c= keyb.nextFloat();
min = a;
if(min > b) min = b;
if(min > c) min = c;
max = a;
SVTH: Nguyn Vn Ph Nhm 12A

Trang 2

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

if(max < b) max=b;


if(max < c) max=c;
if(a!= min && a!= max) System.out.println("So trung gian la
a= " +a);
if(b!= min && b!= max) System.out.println("So trung gian la
b= " +b);
if(c!= min && c!= max) System.out.println("So trung gian la
c= " +c);
}
private void karaoke(){
int a,b,tien=0;
Scanner keyb = new Scanner(System.in);
do{
System.out.print("a= ");
a= keyb.nextInt();
System.out.print("b= ");
b= keyb.nextInt();
}while(b <= a);
if(b <= 18) tien = (b-a)*45000;
else{
if( a <18)
tien = (b - 18)*60000 + (18 - a)*45000;
else tien = (b-a)*60000;
}
System.out.println("So tien phai tra la: " + tien +" VND");
}
private void months(){
int thang,nam,ngay;
Scanner keyb = new Scanner(System.in);
System.out.print("thang: ");
thang= keyb.nextInt();
System.out.print("nam: ");
nam= keyb.nextInt();
if( ((nam % 4)==0 && (nam % 100)!=0) || (nam % 400)==0
){
System.out.println("Nam nhuan co 366 ngay.");
if(thang ==2) System.out.println("Thang 2 co 29
ngay");
}else{
System.out.println("Nam co 365 ngay.");
SVTH: Nguyn Vn Ph Nhm 12A

Trang 3

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

if(thang ==2) System.out.println("Thang 2 co 28


ngay");
}
if( thang ==1 || thang ==3||thang ==5|| thang ==7 ||thang==8
||thang==10|| thang==12)
System.out.println("Thang "+ thang +" co 31 ngay");
else if(thang != 2)
System.out.println("Thang "+ thang +" co 30 ngay");
}

public static void main(String[] args){


int ch;
bai1 b1 = new bai1();
Scanner keyb = new Scanner(System.in);
System.out.print("Danh sach cong viec: \n"
+ "1. Bai1 Giai phuong trinh bac
nhat ax+b=0 \n"
+ "2. Bai2 Giai phuong trinh bac
hai ax2+bx+c=0 \n"
+ "3. Bai3 Tim so trung gian a,b,c
\n"
+ "4. Bai4 Tinh tien karaoke \n"
+ "5. Bai5 In ra so ngay tuong ung
thang nam \n");
System.out.print("Chon cong viec: ");
ch = keyb.nextInt();
switch (ch) {
case 1:
b1.giaipt1();
break;
case 2:
b1.giaipt2();
break;
case 3:
b1.trunggian();
break;
case 4:
b1.karaoke();
break;
case 5:
b1.months();
break;
SVTH: Nguyn Vn Ph Nhm 12A

Trang 4

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

default:
System.out.print("Khong co cong viec!");
break;
}
}
}

Demo
Bi 1 :

Bi 2 :

Bi 3 :

Bi 4 :

SVTH: Nguyn Vn Ph Nhm 12A

Trang 5

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

Bi 5 :

B. CU TRC LP.
6. Vit chng trnh tnh :
S=1+1/2+1/3+....+1/n
7. Vit chng trnh tnh :
S=15-1+1/2-1/3!+....+(-1)n 1/n!
8. Vit chng trnh tnh :
S=1+1/3!+1/5!+..+1/(2n-1)!
9.

Tnh n!!

=
=

1*3*5*..*n(n l)
2*4*6*.*n(n chn)

10. Tnh tng v tch cc ch s ca mt s nguyn dng m cho trc


(V d : m=234=> S=2+3+4=9, P=2*3*4=24)
11. Nhp mt s v kim tra c phi nguyn t khng?
Code :
import java.util.Scanner;

public class bai2 {


private void tinh6(){
float t=0;
int n;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
SVTH: Nguyn Vn Ph Nhm 12A

Trang 6

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

n = keyb.nextInt();
for(int i=1;i<=n;i++){
t += (float) 1/i;
}
System.out.println("Ket qua t= "+t);
}
private void tinh7(){
float t=15;
int n;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
for(int i=1;i<=n;i++){
if( (i%2)==0 ){
t -= (float) 1/i;
}
else t += (float) 1/i;
}
System.out.println("Ket qua t= "+t);
}
private void tinh8(){
float t=1,x=1;
int n;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
for(int i=2;i<=n;i++){
x *= (float) 1/((2*i-1)*(2*i-2));
t+= x;
}
System.out.println("Ket qua t= "+t);
}
private void giaithua(){
int n,t,s=1;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
if((n%2)==0) t=2;
else t=1;
for(int i=t;i<=n;i+=2){
s*=i;
}
SVTH: Nguyn Vn Ph Nhm 12A

Trang 7

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

System.out.print("Giai thua s= " + s);


}
private void sotunhien(){
int n,i=0;
int[] a = new int[10];
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
while(n!=0){
a[i++] = n % 10;
n = n / 10;
}
int tong =0, tich =1;
for(int j=0;j<i;j++){
tong += a[j];
tich *= a[j];
}
System.out.print("Tong la " + tong + "\n" + "Tich la " + tich);
}
private int checknto(int n){
int ok =0;
if(n <= 1) return 0;
else if(n==2) return 1;
else{
for(int i=2;i<=Math.sqrt(n);i++){
if((n%i)==0) ok=1;
}
if(ok!=0) return 0;
else return 1;
}
}
private void nguyento(){
int n,ok=0;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
ok = this.checknto(n);
if(ok==0) System.out.println(n+" khong phai la nguyen to");
else System.out.println(n+" la so nguyen to");
}

SVTH: Nguyn Vn Ph Nhm 12A

Trang 8

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

private void chinhphuong(){


int n,ok=0;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
if(n>1){
for(int i=2;i<=Math.sqrt(n);i++){
if(i*i == n) ok=1;
}
}
if(ok==1) System.out.println(n + " la so chinh phuong");
else System.out.println(n + " khong phai la so chinh phuong");
}
private void doixung(){
int n,ok=0,tam,i=0;
int[] a = new int[10];
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
tam = n;
if(n>1){
while(n!=0){
a[i++] = n % 10;
n = n / 10;
}
if(i%2!=0) System.out.println(tam + " khong doi xung");
else{
for(int j=0;j<i/2;j++){
if(a[j] != a[i-j-1]) ok=1;
}
}
}else ok=1;
if(ok==0) System.out.println(tam + " la so doi xung");
else System.out.println(tam + " khong phai la doi xung");
}
private void showngto(){
int n,ok;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
SVTH: Nguyn Vn Ph Nhm 12A

Trang 9

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

if(n<=1) System.out.println("khong co so nguyen to");


for(int i=2;i<=n;i++){
if(this.checknto(i) == 1)
System.out.print(i+" ");
}
}
private void hoanhao(){
int n,ok,i=0,s=0;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
for(int j=1; j<= n/2;j++){
if(n%j==0) s+=j;
}
if(s==n) System.out.print(n+" la so hoan hao");
else System.out.print(n + " khong hoan hao");
}
private void showFibo(){
int n,ok,s1=1,s2=1;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
System.out.print(s1+" "+ s2+ " ");
do{
System.out.print(s1+s2+" ");
ok=s1; s1=s2; s2+=ok;
n--;
}while(n!=0);
}
private void checkFibo(){
int n,ok=1,s1=1,s2=1,tam;
int[] a= new int[1000];
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
tam =n;
a[0]=1;
int i=1;
do{
a[i++]=s1+s2;
SVTH: Nguyn Vn Ph Nhm 12A

Trang 10

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

ok=s1; s1=s2; s2+=ok;


n--;
}while(n!=0);
for(int j=0;j<i;j++){
if(a[j]==tam) ok=0;
}
if(ok==0) System.out.print(tam+ " la so Fibonasi");
else System.out.print(tam + " khong la Fibonasi");
}
private void UCLN(){
int a,b,c,d;
Scanner keyb = new Scanner(System.in);
System.out.print("a= ");
a = keyb.nextInt();
System.out.print("b= ");
b = keyb.nextInt();
c=a;d=b;
while(c!=d){
if(c>d) c-=d;
else d-=c;
}
System.out.println("UCLN la " + c);
System.out.println("BCNN la " + a*b/c);
}
public static void main(String[] args){
int ch;
bai2 b2 = new bai2();
Scanner keyb = new Scanner(System.in);
System.out.print("Danh sach cong viec: \n"
+ "1. Bai6 Tinh S=1+1/2+..+1/n \n"
+ "2. Bai7 Tinh S=15-1+1/2+..+1/n \n"
+ "3. Bai8 Tinh S=1+1/3!+..+1/(2n-1)!
\n"
+ "4. Bai9 Tinh n! \n"
+ "5. Bai10 Tinh tong va tich cac chu so
cua so tu nhien \n"
+ "6. Bai11 Kiem tra so nguyen to \n");
System.out.print("Chon cong viec: ");
ch = keyb.nextInt();
switch (ch) {
case 1:
SVTH: Nguyn Vn Ph Nhm 12A

Trang 11

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

b2.tinh6();
break;
case 2:
b2.tinh7();
break;
case 3:
b2.tinh8();
break;
case 4:
b2.giaithua();
break;
case 5:
b2.sotunhien();
break;
case 6:
b2.nguyento();
break;
default:
System.out.print("Khong co cong viec!");
break;
}
}
}

Demo:
Bai 6 :

Bi 7 :

SVTH: Nguyn Vn Ph Nhm 12A

Trang 12

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

Bi 8 :

Bi 9 :

Bi 10 :

Bi 11 :

12. Kim tra s P c phi l s chnh phng khng?


13. Kim tra s M c phi l s i xng khng?
14. In ra cc s nguyn t nh hn hoc bng s nguyn dng n cho trc

SVTH: Nguyn Vn Ph Nhm 12A

Trang 13

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

15. In ra cc s hon ho nh hn 1000


( V d : 6=1+2+3, 28=1+2+4+7+14)
16. In ra n ch s Fibonaci u tin
17. Kim tra s K c thuc dy Fibonaci hay khng?
18. Tm c chung ln nht v bi chung nh nht ca 2 s a v b
Code:
import java.util.Scanner;

public class bai3 {


private int checknto(int n){
int ok =0;
if(n <= 1) return 0;
else if(n==2) return 1;
else{
for(int i=2;i<=Math.sqrt(n);i++){
if((n%i)==0) ok=1;
}
if(ok!=0) return 0;
else return 1;
}
}
private void nguyento(){
int n,ok=0;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
ok = this.checknto(n);
if(ok==0) System.out.println(n+" khong phai la nguyen to");
else System.out.println(n+" la so nguyen to");
}
private void chinhphuong(){
int n,ok=0;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
if(n>1){
for(int i=2;i<=Math.sqrt(n);i++){
if(i*i == n) ok=1;
}
}
if(ok==1) System.out.println(n + " la so chinh phuong");
else System.out.println(n + " khong phai la so chinh phuong");
}
private void doixung(){

SVTH: Nguyn Vn Ph Nhm 12A

Trang 14

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

int n,ok=0,tam,i=0;
int[] a = new int[10];
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
tam = n;
if(n>1){
while(n!=0){
a[i++] = n % 10;
n = n / 10;
}
if(i%2!=0) System.out.println(tam + " khong doi xung");
else{
for(int j=0;j<i/2;j++){
if(a[j] != a[i-j-1]) ok=1;
}
}
}else ok=1;
if(ok==0) System.out.println(tam + " la so doi xung");
else System.out.println(tam + " khong phai la doi xung");
}
private void showngto(){
int n,ok;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
if(n<=1) System.out.println("khong co so nguyen to");
for(int i=2;i<=n;i++){
if(this.checknto(i) == 1)
System.out.print(i+" ");
}
}
private int hoanhao(int n){
int ok,i=0,s=0;
for(int j=1; j<= n/2;j++){
if(n%j==0) s+=j;
}
if(s==n) return 1;
else return 0;
}
private void showhoanhao(){
for(int i=2;i<1000;i++){
if(this.hoanhao(i)==1) System.out.print(i+"
}
}
private void showFibo(){
int n,ok,s1=1,s2=1;
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
System.out.print(s1+" "+ s2+ " ");
do{

SVTH: Nguyn Vn Ph Nhm 12A

");

Trang 15

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java


System.out.print(s1+s2+"
ok=s1; s1=s2; s2+=ok;
n--;
}while(n!=0);

");

}
private void checkFibo(){
int n,ok=1,s1=1,s2=1,tam;
int[] a= new int[1000];
Scanner keyb = new Scanner(System.in);
System.out.print("n= ");
n = keyb.nextInt();
tam =n;
a[0]=1;
int i=1;
do{
a[i++]=s1+s2;
ok=s1; s1=s2; s2+=ok;
n--;
}while(n!=0);
for(int j=0;j<i;j++){
if(a[j]==tam) ok=0;
}
if(ok==0) System.out.print(tam+ " la so Fibonasi");
else System.out.print(tam + " khong la Fibonasi");
}
private void UCLN(){
int a,b,c,d;
Scanner keyb = new Scanner(System.in);
System.out.print("a= ");
a = keyb.nextInt();
System.out.print("b= ");
b = keyb.nextInt();
c=a;d=b;
while(c!=d){
if(c>d) c-=d;
else d-=c;
}
System.out.println("UCLN la " + c);
System.out.println("BCNN la " + a*b/c);
}
public static void main(String[] args){
int ch;
bai3 b3 = new bai3();
Scanner keyb = new Scanner(System.in);
System.out.print("Danh sach cong viec: \n"
+ "1. Bai12 Kiem tra so chinh phuong \n"
+ "2. Bai13 Kiem tra so nguyen to \n"
+ "3. Bai14 Kiem tra so doi xung \n"
+ "4. Bai15 In cac so hoan hao \n"
+ "5. Bai16 In ra n so Fibonaci \n"
+ "6. Bai17 Kiem tra so Fibonaci \n"
+ "7. Bai18 Tim UCLN vs BCNN cua a,b \n");

SVTH: Nguyn Vn Ph Nhm 12A

Trang 16

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

System.out.print("Chon cong viec: ");


ch = keyb.nextInt();
switch (ch) {
case 1:
b3.chinhphuong();
break;
case 2:
b3.nguyento();
break;
case 3:
b3.showngto();
break;
case 4:
b3.showhoanhao();
break;
case 5:
b3.showFibo();
break;
case 6:
b3.checkFibo();
break;
case 7:
b3.UCLN();
break;
default:
System.out.print("Khong co cong viec!");
break;
}
}
}

Demo
Bi 12 :

Bi 13 :

SVTH: Nguyn Vn Ph Nhm 12A

Trang 17

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

Bi 14 :

Bi 15 :

Bi 16 :

Bi 17 :

Bi 18 :

SVTH: Nguyn Vn Ph Nhm 12A

Trang 18

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

CHNG 4 :
LP TRNH AWT-SWING
1. Gii phong trnh bc nht.
Code :
package giaodien;
import java.awt.*;
import java.awt.event.*;
public class PTBacNhat extends Frame implements ActionListener {
Panel pn1, pn1_0, pn2, pn3;
Label title, nhapa, nhapb, ketqua;

SVTH: Nguyn Vn Ph Nhm 12A

Trang 19

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

Button tinh, reset, exit;


TextField inputa, inputb, output;
public PTBacNhat() {
this.setLayout(new GridLayout(3, 1));
pn1 = new Panel(new BorderLayout());
pn1_0 = new Panel(new GridBagLayout());
pn2 = new Panel(new GridLayout(3, 2));
pn3 = new Panel(new GridLayout(1, 3));
title = new Label("Giai PT bac nhat");
GridBagConstraints gbc = new GridBagConstraints();
nhapa = new Label("Nhap a");
nhapb = new Label("Nhap b");
ketqua = new Label("Ket qua");
inputa = new TextField();
inputb = new TextField();
output = new TextField();
pn1_0.add(title);
pn1.add(pn1_0, BorderLayout.WEST);
pn2.add(nhapa);
pn2.add(inputa);
pn2.add(nhapb);
pn2.add(inputb);
pn2.add(ketqua);
pn2.add(output);
tinh = new Button("Tinh");
reset = new Button("Reset");
exit = new Button("Exit");
pn3.add(tinh);
pn3.add(reset);
pn3.add(exit);
add(pn1);
add(pn2);
add(pn3);
tinh.addActionListener(this);
reset.addActionListener(this);
exit.addActionListener(this);
setVisible(true);
setSize(300, 300);
}
@Override
public void actionPerformed(ActionEvent arg0) {
Object a = arg0.getSource();
double soa, sob;
if (a == tinh) {
try {
SVTH: Nguyn Vn Ph Nhm 12A

Trang 20

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

soa = Double.valueOf(inputa.getText());
sob = Double.valueOf(inputb.getText());
if (soa == 0)
if (sob == 0)
output.setText("PT vo so
nghiem");
else
output.setText("PT vo nghiem");
else
output.setText("" + -sob / soa);
} catch (Exception e) {
output.setText("Error");
}
}
if (a == reset) {
inputa.setText("");
inputb.setText("");
output.setText("");
inputa.requestFocus();
}
if (a == exit)
System.exit(0);
}
public static void main(String[] args) {
PTBacNhat a = new PTBacNhat();
}
}
Demo :

SVTH: Nguyn Vn Ph Nhm 12A

Trang 21

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

2. Minh ha cc php ton.


Code :
package giaodien;
import java.awt.*;
import java.awt.event.*;
public class pheptoan extends Frame implements ActionListener {
Panel main, pn1, pn2, pn3, pn4;
Label tieude, nhapa, nhapb, ketqua;
Button cong, tru, nhan, chia, exit, reset;
TextField inputa, inputb, output;
public pheptoan() {
main = new Panel(new GridLayout(4, 1));
pn1 = new Panel(new GridBagLayout());
pn2 = new Panel(new GridLayout(3, 2));
pn3 = new Panel(new FlowLayout());
pn4 = new Panel(new FlowLayout());
tieude = new Label("phep toan ");
nhapa = new Label("Nhap a:");
nhapb = new Label("Nhap b:");
SVTH: Nguyn Vn Ph Nhm 12A

Trang 22

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

ketqua = new Label("Ket qua:");


cong = new Button("Cong");
tru = new Button("Tru");
nhan = new Button("Nhan");
chia = new Button("Chia");
exit = new Button("Exit");
reset = new Button("Reset");
inputa = new TextField();
inputb = new TextField();
output = new TextField();
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(0, 0, 0, 300);
pn1.add(tieude, gbc);
pn2.add(nhapa);
pn2.add(inputa);
pn2.add(nhapb);
pn2.add(inputb);
pn2.add(ketqua);
pn2.add(output);
pn3.add(cong);
pn3.add(tru);
pn3.add(nhan);
pn3.add(chia);
pn4.add(exit);
pn4.add(reset);
main.add(pn1);
main.add(pn2);
main.add(pn3);
main.add(pn4);
add(main);
cong.addActionListener(this);
tru.addActionListener(this);
nhan.addActionListener(this);
chia.addActionListener(this);
exit.addActionListener(this);
SVTH: Nguyn Vn Ph Nhm 12A

Trang 23

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

reset.addActionListener(this);
setVisible(true);
setSize(350, 300);
}
@Override
public void actionPerformed(ActionEvent arg0) {
Object a = arg0.getSource();
double soa, sob;
try {
if (a == cong) {
soa = Double.valueOf(inputa.getText());
sob = Double.valueOf(inputb.getText());
output.setText("" + (soa + sob));
}
if (a == tru) {
soa = Double.valueOf(inputa.getText());
sob = Double.valueOf(inputb.getText());
output.setText("" + (soa - sob));
}
if (a == nhan) {
soa = Double.valueOf(inputa.getText());
sob = Double.valueOf(inputb.getText());
output.setText("" + (soa * sob));
}
if (a == chia) {
soa = Double.parseDouble(inputa.getText());
sob = Double.parseDouble(inputb.getText());
output.setText("" + (soa / sob));
}
if (a == exit) {
System.exit(0);
}
if (a == reset) {
inputa.setText("");
inputb.setText("");
output.setText("");
inputa.requestFocus();
}
} catch (Exception e) {
output.setText("Error!");
}
SVTH: Nguyn Vn Ph Nhm 12A

Trang 24

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

}
public static void main(String arg[]) {
pheptoan cal = new pheptoan();
}
}

Code :

3. In cc s nguyn t nh hn hoc bng s n cho trc


Code :
package giaodien;
import java.awt.*;
import java.awt.event.*;
public class nguyento extends Frame implements ActionListener {
Panel main, pn2, pn3, pn1, pn1_0;
Label title, nhap, ketqua;
TextField input, output;
Button tim, reset, exit;
public nguyento() {

SVTH: Nguyn Vn Ph Nhm 12A

Trang 25

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

main = new Panel(new GridLayout(3, 1));


pn1 = new Panel(new BorderLayout());
pn1_0 = new Panel(new GridBagLayout());
pn2 = new Panel(new GridBagLayout());
pn3 = new Panel(new FlowLayout());
title = new Label("Cac so nguyen to <= n:");
nhap = new Label("Nhap n:");
ketqua = new Label("Ket qua:");
input = new TextField();
output = new TextField();
tim = new Button("Tim");
reset = new Button("Reset");
exit = new Button("Exit");
pn1_0.add(title);
pn1.add(pn1_0, BorderLayout.WEST);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
pn2.add(nhap, gbc);
gbc.gridy = 1;
pn2.add(ketqua, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
pn2.add(input, gbc);
gbc.gridy = 1;
pn2.add(output, gbc);
pn3.add(tim);
pn3.add(reset);
pn3.add(exit);
main.add(pn1);
main.add(pn2);
main.add(pn3);
add(main);
tim.addActionListener(this);
reset.addActionListener(this);
exit.addActionListener(this);
setVisible(true);
SVTH: Nguyn Vn Ph Nhm 12A

Trang 26

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

setSize(400, 200);
}
public boolean kiemtra(int i) {
int j;
if (i == 0 || i == 1)
return false;
else if (i == 2)
return true;
else {
for (j = 2; j < i; j++) {
if (i % j == 0)
return false;
}
}
return true;
}
@Override
public void actionPerformed(ActionEvent arg0) {
Object a = arg0.getSource();
Double n;
if (a == tim) {
try {
output.setText("");
n = Double.parseDouble(input.getText());
for (int i = 1; i <= n; i++) {
if (kiemtra(i))
output.setText(output.getText() +
" " + i);
}
} catch (Exception e) {
output.setText("Error!");
}
}
if (a == reset) {
input.setText("");
output.setText("");
input.requestFocus();
}
if (a == exit) {
System.exit(0);
}
SVTH: Nguyn Vn Ph Nhm 12A

Trang 27

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

}
public static void main(String[] arg) {
nguyento nt = new nguyento();
}
}

Demo:

4. Kim tra mt s c thuc dy Fibonaci hay khng?


Code :
package giaodien;
import java.awt.*;
import java.awt.event.*;
public class KTFibonaci extends Frame implements ActionListener {
Panel main, pn1, pn2, pn3;
Label title, nhapa, ketqua;
TextField input, output;
Button OK, Reset, Exit;
KTFibonaci() {
main = new Panel(new GridLayout(3, 1));
pn1 = new Panel(new GridBagLayout());
pn2 = new Panel(new GridLayout(2, 2));
pn3 = new Panel(new FlowLayout());
title = new Label("Kiem tra Fibonaci");
nhapa = new Label("Nhap so ");
ketqua = new Label("KQ");
input = new TextField();

SVTH: Nguyn Vn Ph Nhm 12A

Trang 28

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

output = new TextField();


Exit = new Button("Exit");
Reset = new Button("Reset");
OK = new Button("OK");
Exit.addActionListener(this);
Reset.addActionListener(this);
OK.addActionListener(this);
pn1.add(title);
pn2.add(nhapa);
pn2.add(input);
pn2.add(ketqua);
pn2.add(output);
pn3.add(OK);
pn3.add(Reset);
pn3.add(Exit);
main.add(pn1);
main.add(pn2);
main.add(pn3);
add(main);
}
@Override
public void actionPerformed(ActionEvent arg0) {
Object a = arg0.getSource();
if (a == OK) {
try {
int n = Integer.parseInt(input.getText());
if (kiemtra(n)) {
output.setText(n + " thuoc day
Fibonaci");
} else {
output.setText(n + " khong thuoc day
Fibonaci");
}
} catch (Exception e) {
output.setText("Error!");
}
}
if (a == Reset) {
input.setText("");
output.setText("");
input.requestFocus();
}
SVTH: Nguyn Vn Ph Nhm 12A

Trang 29

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

if (a == Exit) {
System.exit(0);
}
}
public boolean kiemtra(int n) {
int a = 1, b = 1;
while (b < n) {
b = a + b;
a = b - a;
if (b == n)
return true;
}
return false;
}
public static void main(String[] args) {
KTFibonaci a = new KTFibonaci();
a.setVisible(true);
a.setSize(300, 300);
}
}

Demo :

5. M t my tnh in t c nhn.
Demo :

SVTH: Nguyn Vn Ph Nhm 12A

Trang 30

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

package giaodien;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private static final char NULL = 0;
GridBagLayout main_layout, b_layout, b1_layout, b2_layout;
GridLayout b12_layout, b21_layout, b22_layout;
FlowLayout a_layout, b11_layout;
GridBagConstraints gbconstraints;
Container container;
TextField tf;
int group = 0;
JButton backspace, ce, c_c, mc, mr, ms, mcong, cong, tru, nhan,
chia, dau,
cham, can, phantram, nghichdao, bang, hide;
JButton so[] = new JButton[10];
Panel a, b, b1, b2, b11, b12, b21, b22;
public Calculator(String title) {
super(title);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
main_layout = new GridBagLayout();
a_layout = new FlowLayout();
b_layout = new GridBagLayout();
b1_layout = new GridBagLayout();
b2_layout = new GridBagLayout();
b11_layout = new FlowLayout();
b12_layout = new GridLayout(4, 1);
b21_layout = new GridLayout(1, 3);
b22_layout = new GridLayout(4, 5);
gbconstraints = new GridBagConstraints();
a = new Panel();
b = new Panel();
b1 = new Panel();
b2 = new Panel();
b11 = new Panel();
b12 = new Panel();
b21 = new Panel();
SVTH: Nguyn Vn Ph Nhm 12A

Trang 31

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

b22 = new Panel();


tf = new TextField();
backspace = new JButton("Backspace");
hide = new JButton("");
hide.setHideActionText(true);
ce = new JButton("CE");
c_c = new JButton("C");
mc = new JButton("MC");
mr = new JButton("MR");
ms = new JButton("MS");
mcong = new JButton("M+");
for (int i = 0; i <= 9; i++) {
so[i] = new JButton("" + i);
}
cong = new JButton("+");
tru = new JButton("-");
nhan = new JButton("*");
chia = new JButton("/");
dau = new JButton("+/-");
cham = new JButton(".");
can = new JButton("");
phantram = new JButton("%");
nghichdao = new JButton("1/x");
bang = new JButton("=");
container = this.getContentPane();
container.setLayout(main_layout);
gbconstraints.insets = new Insets(5, 5, 5, 5);
gbconstraints.gridx = 0;
gbconstraints.gridy = 0;
gbconstraints.fill = GridBagConstraints.BOTH;
container.add(tf, gbconstraints);
gbconstraints.gridx = 0;
gbconstraints.gridy = 1;
gbconstraints.fill = GridBagConstraints.BOTH;
gbconstraints.insets = new Insets(0, 0, 0, 0);
container.add(create_b_panel(), gbconstraints);
for (int i = 0; i <= 9; i++) {
so[i].addActionListener(this);
}
cong.addActionListener(this);
SVTH: Nguyn Vn Ph Nhm 12A

Trang 32

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

tru.addActionListener(this);
nhan.addActionListener(this);
chia.addActionListener(this);
cham.addActionListener(this);
bang.addActionListener(this);
can.addActionListener(this);
phantram.addActionListener(this);
dau.addActionListener(this);
nghichdao.addActionListener(this);
backspace.addActionListener(this);
ce.addActionListener(this);
c_c.addActionListener(this);
pack();
setVisible(true);
}
JPanel create_a_panel() {
JPanel panel = new JPanel();
panel.setLayout(a_layout);
panel.add(tf);
return panel;
}
JPanel create_b_panel() {
JPanel panel = new JPanel();
panel.setLayout(b_layout);
GridBagConstraints gbconstraints = new
GridBagConstraints();
gbconstraints.gridx = 0;
gbconstraints.gridy = 0;
gbconstraints.insets = new Insets(0, 0, 0, 8);
panel.add(create_b1_panel(), gbconstraints);
gbconstraints.gridx = 1;
gbconstraints.gridy = 0;
gbconstraints.insets = new Insets(0, 0, 0, 0);
panel.add(create_b2_panel(), gbconstraints);
return panel;
}
JPanel create_b1_panel() {
JPanel panel = new JPanel();
panel.setLayout(b1_layout);
SVTH: Nguyn Vn Ph Nhm 12A

Trang 33

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

GridBagConstraints gbconstraints = new


GridBagConstraints();
gbconstraints.gridx = 0;
gbconstraints.gridy = 0;
panel.add(hide, gbconstraints);
gbconstraints.gridx = 0;
gbconstraints.gridy = 1;
panel.add(create_b12_panel(), gbconstraints);
return panel;
}
JPanel create_b2_panel() {
JPanel panel = new JPanel();
panel.setLayout(b2_layout);
gbconstraints.gridx = 0;
gbconstraints.gridy = 0;
panel.add(create_b21_panel(), gbconstraints);
gbconstraints.gridx = 0;
gbconstraints.gridy = 1;
panel.add(create_b22_panel(), gbconstraints);
return panel;
}
JPanel create_b12_panel() {
JPanel panel = new JPanel();
panel.setLayout(b12_layout);
panel.add(mc);
panel.add(ms);
panel.add(mr);
panel.add(mcong);
return panel;
}
JPanel create_b21_panel() {
JPanel panel = new JPanel();
panel.setLayout(b21_layout);
panel.add(backspace);
panel.add(ce);
panel.add(c_c);
return panel;
}
SVTH: Nguyn Vn Ph Nhm 12A

Trang 34

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

JPanel create_b22_panel() {
JPanel panel = new JPanel();
panel.setLayout(b22_layout);
panel.add(so[7]);
panel.add(so[8]);
panel.add(so[9]);
panel.add(chia);
panel.add(can);
panel.add(so[4]);
panel.add(so[5]);
panel.add(so[6]);
panel.add(nhan);
panel.add(phantram);
panel.add(so[1]);
panel.add(so[2]);
panel.add(so[3]);
panel.add(tru);
panel.add(nghichdao);
panel.add(so[0]);
panel.add(dau);
panel.add(cham);
panel.add(cong);
panel.add(bang);
return panel;
}
public static void main(String args[]) {
Calculator a = new Calculator("Calculator");
a.setResizable(false);
a.setLocation(500, 350);
}
@Override
public void actionPerformed(ActionEvent arg0) {
Object click = arg0.getSource();
Object clicktem = click;
JButton tem = new JButton();
JButton da_an = new JButton();
tem = (JButton) clicktem;
StringBuffer chua_chuan;
if (click == ce || click == c_c) {
tf.setText("");
}
/*******************************************/
SVTH: Nguyn Vn Ph Nhm 12A

Trang 35

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

if (click == backspace)
tf.setText(tf.getText().substring(0, tf.getText().length()
- 1));
/*******************************************/
for (int i = 0; i <= 9; i++) {
if (click == so[i] || click == cham) {
group = 1;
tf.setText(tf.getText() + tem.getLabel());
da_an = (JButton) clicktem;
break;
}
}
/*******************************************/
if (click == cong || click == tru || click == nhan || click ==
chia) {
System.out.println(group);
if (group == 2) {
tf.setText((tf.getText()
.substring(0, tf.getText().length() 1))
+ tem.getLabel());
} else {
group = 2;
tf.setText(tf.getText() + tem.getLabel());
da_an = (JButton) clicktem;
}
}
/*******************************************/
if (click == bang) {
try {
String main_text = new String(tf.getText());
if (group == 2 || da_an == cham || da_an == can
|| group == 99
|| group == 4) {
} else {
group = 4;
chua_chuan = new
StringBuffer(tf.getText());
System.out.println("" +
chuanhoa(chua_chuan));
float kq =
tinhtoan(chuanhoa(chua_chuan));
if (kq % 1 == 0)
SVTH: Nguyn Vn Ph Nhm 12A

Trang 36

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

kq = (int) kq;
tf.setText(main_text + "=" + kq);
da_an = (JButton) clicktem;
}
}
catch (Exception e) {
tf.setText("ERROR!");
group = 99;
}
group = 4;
}
}
/*******************************************/
int[] phanloai(StringBuffer a) {
char so[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char pheptinh[] = { '+', '-', '*', '/', '', '%' };
int loai[] = new int[a.length()];
for (int i = 0; i < a.length(); i++) {
for (int j = 0; j <= 9; j++)
if (a.charAt(i) == so[j])
loai[i] = 1;
for (int j = 0; j <= 5; j++)
if (a.charAt(i) == pheptinh[j])
loai[i] = 3;
}
return loai;
}
/*******************************************/
StringBuffer chuanhoa(StringBuffer a) {
StringBuffer chuan = a;
if (chuan.charAt(0) == '-')
chuan.insert(0, "0");
if (chuan.charAt(0) == '.')
chuan.insert(0, "0");
if (chuan.charAt(chuan.length() - 1) == '.')
chuan.append('0');
int i = 0;
do {
int loai[] = phanloai(chuan);
if (chuan.charAt(i) == '.'
&& (loai[i - 1] == 3 && loai[i + 1] ==
3)) {
chuan.replace(i, i + 1, "0.0");
SVTH: Nguyn Vn Ph Nhm 12A

Trang 37

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

}
i++;
} while (i < chuan.length());
i = 1;
do {
int loai[] = phanloai(chuan);
if (chuan.charAt(i) == '.'
&& (loai[i - 1] == 1 && loai[i + 1] ==
3)) {
chuan.insert(i + 1, "0");
}
i++;
} while (i < chuan.length() - 1);
i = 1;
do {
int loai[] = phanloai(chuan);
if (chuan.charAt(i) == '.'
&& (loai[i - 1] == 3 && loai[i + 1] ==
1)) {
chuan.insert(i, "0");
}
i++;
} while (i < chuan.length() - 1);
return chuan;
}
/*******************************************/
float tinhtoan(StringBuffer a) {
int k = 0;
int loai[] = new int[a.length()];
loai = phanloai(a);
for (int i = 0; i < loai.length; i++) {
if (a.charAt(i) == '.')
loai[i] = 1;
}
// Da phan loai xong xau dau vao
StringBuffer tam = new StringBuffer();
float sohang[] = new float[20];
for (int i = 0; i < loai.length; i++) {
if (loai[i] == 1) {
tam.append(a.charAt(i));
continue;
}
if (loai[i] != 1 || i == loai.length - 1) {
SVTH: Nguyn Vn Ph Nhm 12A

Trang 38

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

String v = new String(tam);


sohang[k] = Float.valueOf(v);
k += 2;
tam.delete(0, v.length());
}
}
{
String v = new String(tam);
sohang[k] = Float.valueOf(v);
// Dua phan tu cuoi cung vao
}
int q = -1;
int toantu[] = new int[20];
for (int i = 0; i < loai.length; i++) {
if (loai[i] == 3) {
if (a.charAt(i) == '*') {
q += 2;
toantu[q] = 1;
}
if (a.charAt(i) == '/') {
q += 2;
toantu[q] = 2;
}
if (a.charAt(i) == '+') {
q += 2;
toantu[q] = 3;
}
if (a.charAt(i) == '-') {
q += 2;
toantu[q] = 4;
}
}
}
// Tinh toan
for (int i = 1; i < k; i += 2) {// tinh nhan chia truoc
if (toantu[i] == 1) {
sohang[i - 1] *= sohang[i + 1];
sohang[i + 1] = 0;
toantu[i] = 3;
}
if (toantu[i] == 2) {
sohang[i - 1] /= sohang[i + 1];
sohang[i + 1] = 0;
SVTH: Nguyn Vn Ph Nhm 12A

Trang 39

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

toantu[i] = 3;
}
}
float kq = sohang[0];
for (int i = 0; i <= k; i += 2) {
if (toantu[i + 1] == 3)
kq += sohang[i + 2];
if (toantu[i + 1] == 4)
kq -= sohang[i + 2];
}
return kq;
}
}
Demo :

6. i mu nn.
Code :
package giaodien;
import java.awt.*;
import java.awt.event.*;
public class DoiMau extends Frame implements ActionListener {
Button blue, green, red, exit;
Panel main;
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
Object a = arg0.getSource();
if (a == blue) {
SVTH: Nguyn Vn Ph Nhm 12A

Trang 40

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

main.setBackground(Color.blue);
return;
}
if (a == green) {
main.setBackground(Color.green);
return;
}
if (a == red) {
main.setBackground(Color.red);
return;
}
if (a == exit)
System.exit(0);
}
DoiMau(String t) {
super(t);
main = new Panel(new FlowLayout());
blue = new Button("Blue");
green = new Button("Green");
red = new Button("Red");
exit = new Button("Exit");
main.add(green);
main.add(blue);
main.add(red);
main.add(exit);
add(main);
blue.addActionListener(this);
green.addActionListener(this);
red.addActionListener(this);
exit.addActionListener(this);
setVisible(true);
setSize(300, 200);
}
public static void main(String[] args) {
DoiMau a = new DoiMau("Doi mau nen");
}
}

Demo :
SVTH: Nguyn Vn Ph Nhm 12A

Trang 41

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

7. Minh ha kiu s kin ItemEvent.


Code :
package giaodien;
import java.awt.*;
import java.awt.event.*;
public class ItemEventDemo extends Frame implements ItemListener{
GridBagConstraints gbc;
String xau1 = "", xau2 = "", xau3 = "", xau = "";
GridBagLayout pn1_layout, pn4_layout, pn2_layout;
FlowLayout pn23_layout;
CheckboxGroup group;
Checkbox Female, Male;
Choice choice;
List list;
Panel pn1, pn2, pn3, pn4, main;
Label tf;
Button exit;
ItemEventDemo(String title) {
super(title);
setLayout(new GridLayout(4, 1));
pn1_layout = new GridBagLayout();
pn2_layout = new GridBagLayout();
pn23_layout = new FlowLayout(FlowLayout.CENTER);
pn4_layout = new GridBagLayout();
gbc = new GridBagConstraints();
pn1 = new Panel();
pn4 = new Panel();
pn2 = new Panel();
pn3 = new Panel();
SVTH: Nguyn Vn Ph Nhm 12A

Trang 42

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

pn1.setLayout(pn1_layout);
pn2.setLayout(pn2_layout);
pn3.setLayout(pn23_layout);
pn4.setLayout(pn4_layout);
choice = new Choice();
choice.add("Tiger");
choice.add("Foster");
choice.add("Heiniken");
list = new List(4);
list.add("Mac OS X");
list.add("Windows 7");
list.add("Solaris");
list.add("Ubuntu");
list.add("Windows Vista");
list.add("Windows XP");
list.add("MS DOS");
group = new CheckboxGroup();
Female = new Checkbox("Female", group, true);
Male = new Checkbox("Male", group, false);
exit = new Button("Exit");
tf = new Label("Hay chon cac Item!");
gbc.weightx = 1;
gbc.weighty = 1;
pn1.add(Female, gbc);
gbc.gridx = 1;
pn1.add(Male, gbc);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.ipadx = 250;
gbc.ipady = 10;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 10, 0, 0);
pn4.add(tf, gbc);
gbc.ipadx = 30;
gbc.ipady = 30;
gbc.anchor = GridBagConstraints.EAST;
SVTH: Nguyn Vn Ph Nhm 12A

Trang 43

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

gbc.insets = new Insets(0, 0, 0, 10);


pn4.add(exit, gbc);
gbc.insets = new Insets(0, 100, 0, 100);
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.BOTH;
pn2.add(list, gbc);
pn3.add(choice);
list.addItemListener(this);
choice.addItemListener(this);
Female.addItemListener(this);
Male.addItemListener(this);
exit.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
add(pn1);
add(pn2);
add(pn3);
add(pn4);
setVisible(true);
setSize(400, 300);
}
@Override
public void itemStateChanged(ItemEvent e) {
Object b;
int lit;
if (e.getItemSelectable() == Female)
xau1 = "Female";
if (e.getItemSelectable() == Male)
xau1 = "Male";
if (e.getItemSelectable() == choice) {
b = e.getItem();
xau2 = b.toString();
}
if (e.getItemSelectable() == list) {
b = e.getItem();
lit = Integer.parseInt(b.toString());
if (lit == 0)
xau3 = "Mac OS X";
if (lit == 1)
SVTH: Nguyn Vn Ph Nhm 12A

Trang 44

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

xau3 = "Windows 7";


if (lit == 2)
xau3 = "Solaris";
if (lit == 3)
xau3 = "Ubuntu";
if (lit == 4)
xau3 = "Vista";
if (lit == 5)
xau3 = "Windown XP";
if (lit == 6)
xau3 = "MS DOS";
}
tf.setText("Ban da chon " + xau1 + "..." + xau2 + "..." +
xau3);
}
public static void main(String[] A) {
ItemEventDemo a = new ItemEventDemo("Item Event");
}
}

Demo :

SVTH: Nguyn Vn Ph Nhm 12A

Trang 45

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

CHNG 7 :
LP TRNH C S D LIU
Bi 1 :
Code :
package thSQL_7_1;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
import java.util.Vector;
import com.mysql.jdbc.Statement;
public class mySQL extends JFrame implements ActionListener,
ItemListener {
Panel pn1, pn2,pn3;
JLabel lb1,lb2;
JButton bt1,bt2,bt3;
JTextField tb1;
Choice chon;
CheckboxGroup gr;
Checkbox cb1,cb2,cb3,cb4,cb5;
JTable tb;
JScrollPane tablere;
String tam="MaSo";
String tukhoa;
DefaultTableModel model;
Vector data=new Vector(),title=new Vector();
public mySQL()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
SVTH: Nguyn Vn Ph Nhm 12A

Trang 46

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

{
System.exit(0);
}
});
this.setBounds(100,100,600,300);
setTitle("Select");
getContentPane().setLayout(new
BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
this.setVisible(true);

//

//

//

pn1=new Panel();
pn1.setLayout(new FlowLayout(FlowLayout.CENTER));
pn2=new Panel();
pn2.setLayout(new FlowLayout(FlowLayout.CENTER));
pn3=new Panel();
pn3.setLayout(new FlowLayout());
this.add(pn1);
this.add(pn2);
this.add(pn3);
lb1=new JLabel();
lb1.setText("Nhao noi dung");
pn1.add(lb1);
tb1=new JTextField("nhap thong tin tim kiem");
pn1.add(tb1);
bt1=new JButton("Tim kiem");
bt1.addActionListener(this);
bt1.setLabel("Tim kiem");
pn1.add(bt1);
bt2=new JButton("Reset");
bt2.addActionListener(this);
bt2.setLabel("Reset");
pn1.add(bt2);
bt3=new JButton("Exit");
bt3.addActionListener(this);
bt3.setLabel("Exit");
pn1.add(bt3);
lb2=new JLabel();
lb2.setText("Tim kiem theo");
pn2.add(lb2);
gr=new CheckboxGroup();
cb1=new Checkbox("MaSo",gr,true);

SVTH: Nguyn Vn Ph Nhm 12A

Trang 47

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

cb1.addItemListener(this);
pn2.add(cb1);
cb2=new Checkbox("HoTen",gr,false);
cb2.addItemListener(this);
pn2.add(cb2);
cb3=new Checkbox("NgaySinh",gr,false);
cb3.addItemListener(this);
pn2.add(cb3);
cb4=new Checkbox("DiaChi",gr,false);
cb4.addItemListener(this);
pn2.add(cb4);
cb5=new Checkbox("GioiTinh",gr,false);
cb5.addItemListener(this);
pn2.add(cb5);
truyvan(tam,"");
model=new DefaultTableModel(data,title);
tb=new JTable(model);
tablere=new JScrollPane(tb);
pn3.add(tablere);

this.pack();

}
public void truyvan(String tam,String tukhoa)
{
data.clear();
title.clear();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection qr =
DriverManager.getConnection("jdbc:mysql://localhost:3306/thjava","root",
"123456");
java.sql.Statement state=qr.createStatement();
ResultSet rs=state.executeQuery("select * from thjava7_1");
ResultSetMetaData rsd=rs.getMetaData();
int column=rsd.getColumnCount();
for(int i=1;i<=column;i++)
SVTH: Nguyn Vn Ph Nhm 12A

Trang 48

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

{
title.add(rsd.getColumnLabel(i));
}
while(rs.next())
{
Vector row=new Vector(column);
row.add(rs.getInt("MaSo"));
row.add(rs.getString("HoTen"));
row.add(rs.getString("NgaySinh"));
row.add(rs.getString("DiaChi"));
row.add(rs.getString("GioiTinh"));
if(sosanh(rs.getString(tam),tukhoa))data.add(row);
}
rs.close();
state.close();
qr.close();
}
catch(Exception e){System.out.println(e);}
}
public boolean sosanh(String a,String b)
{
a=a.toLowerCase();
b=b.toLowerCase();
if(a.indexOf(b)!=-1) return true;
return false;
}

public static void main(String[] args) {


// TODO Auto-generated method stub
mySQL mysql=new mySQL();
}

@Override
SVTH: Nguyn Vn Ph Nhm 12A

Trang 49

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

public void itemStateChanged(ItemEvent arg0) {


// TODO Auto-generated method stub
tam=arg0.getItem().toString();
System.out.println(tam);
}

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getActionCommand().equals("Tim kiem"))
{
truyvan(tam,tb1.getText());
model.fireTableDataChanged();
System.out.println("tim kiem");
}
else if(arg0.getActionCommand().equals("Reset"))
{
data.clear();
title.clear();
model.fireTableDataChanged();
}
else if(arg0.getActionCommand().equals("Exit"))
{
System.exit(0);
}
}
}

Demo :

SVTH: Nguyn Vn Ph Nhm 12A

Trang 50

Thc hnh Lp Trnh Java

GVHD: Ths.Mai Vn H

Bi 2 :
Code :
package thSQL_7_2;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Collection;
import java.util.Vector;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class DataBaseSQL extends JFrame implements ActionListener {

JTextField tf1;
JTextField tf2;
Vector data=new Vector(),title=new Vector();
JScrollPane spn;
DefaultTableModel model;

SVTH: Nguyn Vn Ph Nhm 12A

Trang 51

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

public DataBaseSQL ()
{
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(100, 100, 800, 300);
this.setVisible(true);
getContentPane().setLayout(new
BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
JPanel pn1=new JPanel();
pn1.setLayout(new FlowLayout());
JLabel lb1=new JLabel();
lb1.setText("Nhap Noi Dung");
tf1=new JTextField(20);
pn1.add(lb1);
pn1.add(tf1);
this.add(pn1);
JPanel pn2=new JPanel();
pn2.setLayout(new FlowLayout());
JLabel lb2=new JLabel();
lb2.setText("SQL");
tf2=new JTextField(20);
pn2.add(lb2);
pn2.add(tf2);
this.add(pn2);

truyvan("com.mysql.jdbc.Driver","select * from
khachhang");
JPanel pn3=new JPanel();
model =new DefaultTableModel(data,title);
JTable tb=new JTable(model);
spn=new JScrollPane(tb);
pn3.add(spn);
this.add(pn3);
Panel pn4=new Panel();
JButton bt1=new JButton("Submit");
bt1.addActionListener(this);
pn4.add(bt1);
JButton bt2=new JButton("Reset");
bt2.addActionListener(this);
pn4.add(bt2);
SVTH: Nguyn Vn Ph Nhm 12A

Trang 52

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

JButton bt3=new JButton("Cancel");


bt3.addActionListener(this);
pn4.add(bt3);
this.add(pn4);
this.pack();

}
public void truyvan(String jdbc,String sql)
{
data.clear();
title.clear();
try
{
Class.forName(jdbc);
Connection cn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/thjava","root",
"123456");
Statement st =cn.createStatement();
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rsdt=rs.getMetaData();
int column = rsdt.getColumnCount();
for(int i=1;i<=column;i++)
{
title.add(rsdt.getColumnLabel(i));
}
while(rs.next())
{
Vector row =new Vector();
row.add(rs.getInt("ID"));
row.add(rs.getString("tenkhachhang"));
row.add(rs.getString("diachi"));
row.add(rs.getString("sanpham"));
data.add(row);
}
rs.close();
st.close();
cn.close();
}
catch(Exception e)
{
System.out.println(e);
SVTH: Nguyn Vn Ph Nhm 12A

Trang 53

GVHD: Ths.Mai Vn H

Thc hnh Lp Trnh Java

}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new DataBaseSQL();
}
@Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand().equals("Submit"))
{
truyvan(tf1.getText(),tf2.getText());
model.fireTableDataChanged();
}
else if(arg0.getActionCommand().equals("Reset"))
{
data.clear();
title.clear();
model.fireTableDataChanged();
}
else if(arg0.getActionCommand().equals("Cancel"))
{
System.exit(0);
}
// TODO Auto-generated method stub
}
}

Demo :
SVTH: Nguyn Vn Ph Nhm 12A

Trang 54

Thc hnh Lp Trnh Java

SVTH: Nguyn Vn Ph Nhm 12A

GVHD: Ths.Mai Vn H

Trang 55

You might also like