Java Programming Part 2

34
Re-compiled by: Mr. HIEENG Sokh Hymns 1 Chapter 7 Packages and Interfaces 1. Packages កច ប់សំប់វវចចប់ class និង interface1.1. How to create packages Form: package packageName; ឧហរណ៍៖ package p1; class Simple{ int a; int b; } 1.2. Import package Form: import packageName.className; ឧហរណ៍៖ package p1; import Review.Sub1; public class Main{ public static void main(String[] args){ Sub1 obj1=new Sub1(); Review.Sub2 obj2=new Review.Sub2(); Review.Sub2 obj3=new Review.Sub2(); Simple obj4=new Simple(); Review.Simple obj5=new Review.Simple(); } }

description

in khmer

Transcript of Java Programming Part 2

Re-compiled by: Mr. HIEENG Sokh Hymns 1

Chapter 7

Packages and Interfaces

1. Packages

ជាកញ្ច ប់សំរាប់វវចខ្ចប់ class និង interface។ 1.1. How to create packages

Form:

package packageName;

ឧទាហរណ៍៖

package p1;

class Simple{

int a;

int b;

}

1.2. Import package

Form:

import packageName.className;

ឧទាហរណ៍៖ package p1;

import Review.Sub1;

public class Main{

public static void main(String[] args){

Sub1 obj1=new Sub1();

Review.Sub2 obj2=new Review.Sub2();

Review.Sub2 obj3=new Review.Sub2();

Simple obj4=new Simple();

Review.Simple obj5=new Review.Simple();

}

}

Re-compiled by: Mr. HIEENG Sokh Hymns 2

ចំណ៖ំ

យយើងអាចយក class ពី package វផេងបានវោយពីរវធីិ៖ 1. វរបើ keyword import ដែលមានលកខណៈស្សវែៀង Header file វៅកនុងភាសា C ឬ C++

វែើមបីទាញយក class វ ោះ និងបញ្ជជ ក់ពី package ។ 2. វយើងមិនចំបាច់វរបើ keyword import ក៏បានដែរ ដែវយើងចំបាច់រែូវបញ្ជជ ក់ package

វ ោះររប់វពលដែលវយើងវរបើ class វ ោះ។

JComboBox ជា class សថិែកនុង package javax.swing.JComboBox ដែល class JComboBox

រឺជា Components ដែលអាចផទុកទិននន័យបានវរចើន Items មានលកខណៈជា Drop-down List ឧទាហរណ៍៖

JComboBox combo=new JComboBox();

វៅកនុង class JComboBox មាន Method ជាវរចើនែូចជា៖ void setEditable(boolean); ជា method មានែួ ទីអាចឲ្យ User ដកដរបទិននន័យវៅកនុង

ComboBox បាន។ ឧទាហរណ៍៖ combo.setEditable(true);

void setMaximumRowCount(int); ជា method មានែួ ទីកំណែ់ចំនួន Item វរចើនបំផុែ ដែលរែូវបានបង្ហា ញវៅកនុង Drop-down List ។ ឧទាហរណ៍៖ combo.setMaximumRowCount(5);

int getItemCount(); ជា method មួយមានែួ ទីរាប់ចំនួន Item មានកនុង ComboBox ។ ឧទាហរណ៍៖ int numItems;

numItems = combo.getItemCount();

// get numbers of Items in JComboBox

void setSelectedIndex(int); ជា method មួយមានែួ ទីបវងកើែការ Select Item ណាមួយ តាម Index ដែលវយើងបានកំណែ់។ ឧទាហរណ៍៖

combo.setSelectedIndex(3);

Object getSelectedItem();ជា method មួយមានែួ ទីទាញយក Item ដែល User បាន Select ។

Re-compiled by: Mr. HIEENG Sokh Hymns 3

ឧទាហរណ៍៖ String item;

item = (String) combo.getSelectedItem();

Object getItemAt(int); ជា method មួយមានែួ ទីទាញយក Item ដែលសថិែវៅកនុង Index ណាមួយ។ ឧទាហរណ៍៖

String item;

item = (String) combo.getItemAt(3);

void addItem(object); ជា method មួយមានែួ ទី add Item ចូល ComboBox ។ ឧទាហរណ៍៖

String item;

item = “Teacher”;

combo.addItem(item);

combo.addItem(“Student”);

private void cmdAddActionPerformed(Java,…,…..){

string item;

item = txtAdd.getText();

combo.addItem(item);

txtAdd.setText(“ ”);

txtAdd.grabFocus();

int last;

last = combo.getItemCount() -1;

combo.setSelectedIndex(last);

}

void insertItemAt(object, int); ជា method មួយមានែួ ទីរបវររៀែ Item ថ្មីចូលកនុង ComboBox។ ឧទាហរណ៍៖

String item;

txtAdd cmdAdd

combo

Re-compiled by: Mr. HIEENG Sokh Hymns 4

item = “New Item”;

combo.insertItemAtt(item, 3);

void removeItemAt(int); void removeItem(object); void removeAllItems(); ឧទាហរណ៍៖

combo.removeItemAt(3);

combo.removeItem(“Student”);

combo.removeAllItems();

Homework:

ចូរសរវសរ Program វែើមបី Add ទិននន័យចូលកនុង ComboBox ។ ទិននន័យដែលរែូវបាន Add រែូវវរៀបតាមលំោប់វោយសវ័យរបវែតិ (A → Z) ។ មិនអនុញ្ជា ែឲ្យទិននន័យរចំដែល ឬទវទ វៅកនុង ComboBox វទ។

Correction:

1. វរៀបតាមលំោប់វោយសវ័យរបវែតិ (A → Z)

private void cmdAddActionPerformed(java.awt.event...)

String item;

Item = txtAdd.getText().trim();

String itemCom;

itemCom = (String) combo.getItemAt(0);

if(item.equals(itemCom)){

// item == itemCom

}else{

// item != itemCom

}

TextField

ComboBox

CammandAdd

Re-compiled by: Mr. HIEENG Sokh Hymns 5

if(item.compareTo(itemCom)<0){

// item<itemCom

}else if(item.CompareTo(itemCom)>0){

// item>itemCom

}else{

// item == itemCom

}

2. មិនអនុញ្ជា ែឲ្យទិននន័យរចំដែល ឬទវទ វៅកនុង ComboBox

3. សរវសរកំុឲ្យសទួនគ្នន វោយខ្លួនឯង (Check in C++ រែង់ចំណុច code already exist)

25 – June – 2011

1.3. Inheritance in Different Package

Package p1

public class Simple{

int a;

int b;

}

package inheritance;

import p1.Simple;

public class SubSimple extends Simple{

int x;

int y;

}

1.4. Nested Package

package p1.Sub1; // Nested package.

1.5. Access Control

Private NoModifier Protected Public

Same class yes yes yes yes (1st)

Same package SubClass no yes yes yes (2nd

)

Same package noSubClass no yes yes yes (3rd

)

Different package SubClass no no yes yes (4th

)

Different package noSubClass no no no yes (5th

)

Re-compiled by: Mr. HIEENG Sokh Hymns 6

ឧទាហរណ៍អំពី Same class(1st)៖

package accessControl;

public class Access{

private int a;

int b;

protected int c;

public int d;

public Access(){

a = 1;

b = 1;

c = 1;

d = 1;

}

}

ឧទាហរណ៍អំពី Same package SubClass (2nd

)៖ public class SubAccess extends Access{

public SubAccess(){

// a = 1; can’t use private

b = 1;

c = 1;

d = 1;

}

}

ឧទាហរណ៍អំពី Same package noSubClass (3rd

)៖ public class NoSubAccess{

publicNoSubAccess(){

Access obj = new Access();

// obj.a = 1; can’t use private

obj.b = 1;

obj.c = 1;

obj.d = 1;

}

}

Re-compiled by: Mr. HIEENG Sokh Hymns 7

ឧទាហរណ៍អំពី Different package SubClass (4th

)៖ import accessControl.Access;

public class DiffSubAccess extends Access{

public DiffSubAccess(){

// a = 1; can’t use private

// b = 1; can’t use NoModifier

c = 1;

d = 1;

}

}

ឧទាហរណ៍អំពី Different package noSubClass (5th

)៖ import accessControl.Access;

public class DiffNoSubAccess{

public DiffNoSubAccess(){

Access obj = new Access();

// obj.a = 1; can’t use private

// obj.b = 1; can’t use NoModidier

// obj.c = 1; can’t use protected

obj.d = 1;

}

}

2. Interface

រឺជា class ដែលមាន instance variable សុទធដែ Final value និង method សុទធដែជា abstract (ជា method ដែលមិនវពញវលញ) ។

2.1. How to create interface

Form:

AccessControl interface InterfaceName{

type-Final instanceVariable = final-Value;

return-type methodName(arg);

}

Re-compiled by: Mr. HIEENG Sokh Hymns 8

ឧទាហរណ៍៖

public interface Inter1{

public int VALUE_A = 20;

public void showA();

}

2.2. Implementing interface

វែើមបីទាញយក member របស់ interface មកវរបើវៅកនុង class វយើងចំបាច់រែូវវរបើ keyword “implements” ។

package Interface;

public interface Inter1{

public int VALUES_A = 10;

public void showA();

}

package Interface; public class SubInter implements Inter1{

public void showA(){

System.out.println(VALUES_A);

}

}

package Interface; public class SubInter implements Inter1{

public void showA(){

System.out.println(VALUES_A);

}

}

Re-compiled by: Mr. HIEENG Sokh Hymns 9

package Interface; public class Main{

public static void main(String[] args){

SubInter obj1 = new SubInter();

System.out.println(obj1.VALUES_A);

obj1.showA();

Inter1 obj2 = new Inter1(){

Public void showA(){

System.out.println(VALUES_A);

}

}

obj2.showA();

}

}

JRadioButton ជា class ដែលសថិែវៅកនុង Package Javax.swing.JRadioButton ។ class

JRadioButton ជា Components ដែលអនុញ្ជា ែិឲ្យ Users វររើសវរ ើស Option ណាមួយ ដែលពួកវរចង់បាន។

ឧទាហរណ៍៖ JRadioButton radio = new JRadioButton(); កនុង class JRadioButton មាន method 2 ដែលសំខាន់៖

void setSelected(Boolean); ជា method ដែលមានែួ ទីបវងកើែ Select ឲ្យ RadioButton ។ ឧទាហរណ៍៖

Radio.setSelected(true);

boolean isSelected();ជា method ដែលមានែួ ទីវផទៀងផ្ទទ ែ់វមើលថាRadio

Buttonរែូវបាន Select ឬអែ់។ ឧទាហរណ៍៖

if(radio.isSelected()){

// radio has selected

}else{

// radio has not selected

}

Re-compiled by: Mr. HIEENG Sokh Hymns 10

Homework:

ចូរសរវសរ Program វែើមបី input ទិននន័យែូចរូបខាងវលើ វហើយទិននន័យដែល User

បញ្ចូ លរែូវធ្លល ក់ចុលកនុង Text area វៅវពល User click button Add ។

2.3. Multi Inheritance with Inheritance

package Interface;

public class SubInter implements Inter1, Inter2{

public void showA(){

System.out.println(VALUES_A);

}

public void showB(){

System.out.println(VALUES_B);

}

}

Gender

First Name:

សLast Name:

Male Female

Country ComboBox Add

First Name Last Name Gender Country

Re-compiled by: Mr. HIEENG Sokh Hymns 11

package Interface;

public interface MainInter extends Inter1, Inter2{

public inter VALUES_C = 89;

public void showC();

}

ចំណ៖ំ វយើងអាច Inheritance បាន ៣យ៉ាងវោយវរបើ 2 Keywords រឺ៖ Keywords “extends”

និង “implements” ។ វបើ class ទទួលមរែកពី class វយើងចំបាច់វរបើ Keyword “extend” ។ វបើ interface ទទួលមរែកពី interface វយើងចំបាច់វរបើ Keyword “extend” ។ វបើ class ទទួលមរែកពី interface វយើងចំបាប់វរចើ Keyword “implements” ។

សង្ខេប៖

class extends class interface extends interface class implements interface

Interface មិនអាចទទួល Member ពី Class បានវទ វោយសារដែវៅកនុង class មាន Normal instanceVariable និង Normal Method ។

2.4. Inheritance versus Abstract class

package Inheritance;

public interface Interface{

public int VALUES=10;

// public int x; can’t create Normal instanceVariable

// public void show();

// public void showValues(){

can’t create Normal Method

}

}

Re-compiled by: Mr. HIEENG Sokh Hymns 12

Package Interface;

Public abstract class Abstract{

Final public int VALUES = 90;

Public int value;

Abstract public void show();

Public void showValue(){

Systeml.out.println(value);

}

}

The End !

Re-compiled by: Mr. HIEENG Sokh Hymns 13

Chapter 8

Exception Handling

1. The Exception Hierarchy

កនុងភាសា Java វយើងមាន code សំរាប់សរវសរ error ដែវបើវៅដែមាន error វយើងអាចបំ បាែ់ error ទំាងអស់វ ោះបាន។

Class throwable មានែួ ទីររប់ររងររប់ error ទំាងអស់ដែលវកើែមានវឡើង។ error ទំាង វ ោះដចកវចញជាពីរ៖

Exception

ArithmeticException

NumberFormatException

ArrayIndexOutOfBoundsException

ArrayStroeException

SQLException

ClassNotFoundException

Other class

Error (JVM = Java Virtual Machine)

ចំណំា៖

throwable : ជា SuperClass របស់ class Exception និង Error ។ Exception ជា class មួយមានែួ ទីការពារ error កំរែិស្សាលដែលភារវរចើនបណាត ល មកពី code ឬ user input ។ Error វនោះរបវភទវនោះវយើងអាចការពារបានទំាងស្សុងវោយ រគ្នន់ដែវរបើ try, catch វែើមបី throw error វចល។

Errorជា class ដែលររប់ររងវលើ error របវភទធងន់ដែលបណាត លមកពី Hardware ឬ Software machine ។ Error របវភទវនោះវយើងមិនអាចការពារបានវទ។ ឧទាហរណ៍៖

Out of memory Not found hard disk

2. Using try, catch keyword

Form:

try{

// block of code to monitor for errors

Re-compiled by: Mr. HIEENG Sokh Hymns 14

}catch(Exception-type 1 obj){

// block exception type 1

// this block executed when has error

// of Exception type 1

}catch(Exception-type 2 obj){

// block Exception type 2

// this block executed when has errors

// of Exception type 2

}finally{

// this block always executed

}

ឧទាហរណ៍៖ private void ...

try{

int a[]={10,20,30,40,50};

int n;

n=Integer.valueOf(txtNumber.getText().trim());

int index;

index=Integer.valueOf(txtIndex.getText().trim());

int dive;

div=a[index]/n;

txt.setText(“Your result is ”+div.);

}catch(NumberFormatException e){

JOptionPan.showMessageDialog(this, “Please, ....”);

}catch(ArrayIndexOutOfBoundsException e){

JOptionPane.showMessageDialog(this, “Please, ....”);

}catch(ArithmeticException e){

JOptionPane.showMessageDialog(this, “Please, divide by zero.”);

}catch(Exception e){

JOptionPane.showMessageDialog(this,e.getMassage());

}

The End !

Re-compiled by: Mr. HIEENG Sokh Hymns 15

09 – July – 2011

Chapter 9

Input and Output

1. java.io.* ជា package ដែលរបមូលផតុំវៅវោយ class ដែលអាច input និង output ។

2. File ជាclass ដែលសថិែវៅកនុង package java.io.File មានែួ ទីររប់ររងពែ៌មានទំាងអស់ របស់ file ឬ directory ។

Form:

File objF = new File(String pathName);

pathName; ជា address និងវ ម្ ោះរបស់ file ឬ directory ។

objF; ជា object ដែលវកើែវចញពី class File មានែួ ទីយកពែ៌មានរបស់ file ឬ directory

ឧទាហរណ៍៖ File objF = new File(“C:\\myPro\\My File\\text.txt”);

Or

File objF = new File(“C:/myPro/My File/text.txt”);

File objD = new File(“C:\\myPro\\My File”);

Or

File objD = new File(“C:/myPro/My File”);

វែើមបីទាញយកពែ៌មានរបស់ file ឬ directory វយើងចំបាច់រែូវវរបើ method ែូចខាងវរកាម៖ String getName(); ជា method មានែួ ទីទទួលយកវ ម្ ោះរបស់ file ឬ directory ។ ឧទាហរណ៍៖

String nameF, nameD;

nameF=objF.getName(); // nameF= “text.txt”

nameD=objD.getName(); // nameD= “My File”

String getParent();ជា method មានែួ ទីទទួលយករែឹមដែ address របស់ file ឬ

directory ។ ឧទាហរណ៍៖

String parentF, parentD;

Re-compiled by: Mr. HIEENG Sokh Hymns 16

parentF=objF.getParent (); // parentF= “C:/myPro/My File”

parentD=objD.getParent (); // parentD= “C:/myPro”

09 – July – 2011

String getPath();ជា method មានែួ ទីទទួលយកទំាង Address និងវ ម្ ោះ របស់ File

ឬ Directory ឧទាហរណ៍៖

String pathF, pathD;

pathF=objF.getPath (); // pathF= “C:/myPro/My File/text.txt”

pathD=objD.getPath (); // pathD = “C:/myPro/My File”

String getAbsolutePath();ជា method មានែួ ទីទទួលយក Path បានជាក់ចាស់ជាង

Method getPath ។ ឧទាហរណ៍៖

File objF=new File(“MyFile/text.txt”);

String path,abPath;

Path=objF.getPath(); // path=“MyFile/text.txt”

abPath()=objF.getAbsolutePath(); // abPath=“C:/myPro/My File/text.txt”

String getCanocicalPath(); ជា method មានែួ ទីទទួលយកPath បានជាក់ចាស់ជាង getAbsolutePath ។ ឧទាហរណ៍៖

File objF=new File(“…/text.txt”);

String abPath, canPath;

abPath=objF.getAbsolutePath(); // “c:/MyPro/…/text.txt”

canPath()=objF.getCanonicalPath(); // “C:/text.txt”

16 – July – 2011

boolean mkdir(); ជា method មានែួ ទីបវងកើែ Directory វបើ return true Directory

វ ោះរែូវបានបវងកើែវហើយ។ ឧទាហរណ៍៖

File objD=new File(“C:/myPro/New Directory”);

objD.mkdir();

boolean mkdirs(); ជា method មានែួ ទីបវងកើែទំាង Root Directory និង Sub-directory ឧទាហរណ៍៖

File objD=new File(“C:/myPro/Sub/Sub1/Sub2”);

Re-compiled by: Mr. HIEENG Sokh Hymns 17

objD.mkdirs();

boolean createNewFile();ជា method មានែួ ទីបវងកើែ File ថ្មី វបើ Return true File វ ោះ រែូវបានបវងកើែ។ ឧទាហរណ៍៖

File objF=new File(“C:/myPro/My File/text.txt”);

objF.createNewFile();

boolean exists();ជា method មានែួ ទីវផទៀងផ្ទទ ែ់វមើល ថាវែើ Directory ឬ File

មានវៅកនុង របព័នធឬអែ់? វបើមានវា Return true ។ ឧទាហរណ៍៖

File objF=new File(“C:/myPro/My File/text.txt”);

if(objF.exists())

System.out.println(“This file is existed.”);

else

System.out.println(“This is not existed.”);

boolean delete(); ជា method មានែួ ទីdelete file វចញពី System។ វបើ return true File

វ ោះរែូវបាន delete ។ ឧទាហរណ៍៖

File objF=new File(“C:/myPro/My File/text.txt”);

if(objF.delete())

System.out.println(“Deleted.”);

else

System.out.println(“Can’t deleted.”);

boolean isFile();ជា method មានែួ ទីវផទៀងផ្ទទ ែ់វមើល ថាវែើ object វ ោះជា obj របស់

File ឬក៏មិនដមន? វបើជា object fileវា Return true ។ ឧទាហរណ៍៖

File objF=new File(“C:/myPro/My File/text.txt”);

if(objF.isFile())

System.out.println(“This is file.”);

else{

System.out.println(“This is not file.”);

Re-compiled by: Mr. HIEENG Sokh Hymns 18

}

boolean isDirectory(); ជា method មានែួ ទីវផទៀងផ្ទទ ែ់វមើល ថាវែើ object វ ោះជា obj

របស់ File ឬក៏មិនដមន? វបើជា object directory វា Return true ។ ឧទាហរណ៍៖

File objD=new File(“C:/myPro/My File”);

if(objD.isDirectory())

System.out.println(“This is directory.”);

else{

System.out.println(“This is not directory.”);

}

boolean renameTo(File F);ជា method មានែួ ទីRename File ឬផ្ទល ស់បតូរ File វៅកាន់ ទីតំាងថ្មី។ ឧទាហរណ៍៖

File objF=new File(“C:/myPro/My File/text.txt”);

File objNew=new File(“D:/newFile.txt”);

objF.renameTo(objNew); // Rename and move to D:\newFile.txt

String[] list();ជា method មានែួ ទីបង្ហា ញ Part របស់ Directory និង File ដែលសថិែ វៅកនុងទីតំាងណាមួយ។ ឧទាហរណ៍៖

File objD=new File(“C:/myPro”);

String path[];

path=objD.list();

for(int i=0; i<path.length; i++)

System.out.println(path[i]);

file[] listFiles(); ជា method មានែួ ទីទាញយក Object Directory និង Object File

ដែលសថិែ វៅកនុងទីតំាងណាមួយ។ ឧទាហរណ៍៖

File objD=new File(“C:/myPro”);

File f[];

f=objD.listFiles();

for(int i=0; i<f.length; i++)

f[i].delete();

Re-compiled by: Mr. HIEENG Sokh Hymns 19

long length(); ជា method មានែួ ទីទទួលយកទំហំរបស់ File ដែលខាន ែរិែជា byte ។ long getTotalSpace(); ជា method មានែួ ទីទទួលយកទំហំសរុបរបស់ Drive ណា មួយដែលខាន ែរិែជា byte ។

long getUsableSpace(); ជា method មានែួ ទីទទួលយក Space ពី Drive ណាមួយ ដែលខាន ែរិែជា byte ។

23 – July – 2011

3. FileInputStream ជា class ដែលសថិែវៅកនុង Package java.io.FileInputStream មានែួ ទី Read

ទិននន័យជា File ។

*.BufferedInputStream ជា class ដែលសថិែវៅកនុង Package java.io.BufferedInputStream មាន ែួនទីបវងកើែទីតំាងបំរងុទុកសំរាប់ Read ទិននន័យជា File ។ *.Scannerជា class ដែលសថិែវៅកនុង Package java.util.Scannerមានែួ ទី Read ទិននន័យជា File បានររប់ DataTypes ជាពិវសស DataTypes របវភទជា String ។ ឧទាហរណ៍៖ How to Read File.wmv

public class WriteRead{

public static void main(String arg[]){

try{

File f=new File(“java.txt”);

FileInputStream fi=new FileInputStream(f);

BufferedInputStream bi=new BufferedInputStream(fi);

Scanner sc=new Scanner(bi);

While(sc.hasNext()){

System.out.println(sc.nextLine());

}

}catch(Exception e){}

}

}

4. FileOutputStreamជា class ដែលសថិែវៅកនុង Package java.io.FileOutputStream មានែួ ទី Write ទិននន័យចូល File ។

Re-compiled by: Mr. HIEENG Sokh Hymns 20

*.BufferedOutputStream ជា class ដែលសថិែវៅកនុង Package java.io.BufferedOutputStream

មានែួ ទីបវងកើែទីតំាងបំរងុទុកសំរាប់ Write ទិននន័យចូល File ។ *.PrintStream ជា class ដែលសថិែវៅកនុង Package java.io.PrintStream មានែួ ទីអាច Write

ជា String ចូលកនុង File ។ ឧទាហរណ៍៖ How to Write File.wmv

public class WriteRead{

public static void main(String arg[]){

try{

File f=new File(“Data.txt”);

FileOutputStream fo=new FileOutputStream(f,true);

BufferedOutputStream bo=new BufferedOutputStream(fo);

PrintStream ps=new PrintStream(bo);

ps.println();

ps.println(“Hello, Java Programming”);

ps.println(“What subject do you study?”);

ps.close();

bo.close();

fo.close();

}catch(Exception e){}

}

} *.FileWriterជា class ដែលសថិែវៅកនុង Package java.io.FileWriter មានែួ ទី Write ទិននន័យ ជា String ចូលកនុង File វហើយវាមិនចំបាច់រែូវការ File OutputStream និង BufferedOutput

Stream វទ។ ឧទាហរណ៍៖ How to Write File with FileWriter.wmv

public class WriteRead{

public static void main(String arg[]){

try{

File f=new File(“Data.txt”);

FileWriter fw=new FileWriter(f,true);

fw.write(“How are you?\r\n”);

fw.write(“I’m well.\r\n”);

fw.close();

}catch(Exception e){}

Re-compiled by: Mr. HIEENG Sokh Hymns 21

}

} How to Write and Read 1 Record.wmv

Label: Name TextField

Label: Age TextField

Address TextField

Command Save

Command Open

public class WriteRead{

public static void main(String arg[]){

try{

File f=new File(“MyData.txt”);

FileInputStream fi=new FileInputStream(f);

BufferedInputStream bi=new BufferedInputStream(fi);

Scanner sc=new Scanner(bi);

String st;

st=sc.nextLine();

String d[];

d=st.split(“;”,3);

txtName.setText(d[0]);

txtAge.setText(d[1]);

txtAddress.setText(d[2]);

}catch(Exception e){}

}

}

JTable Format

Label: First Name: TextField

Last Name: TextField

Date of Birth: TextField

Country: ComboBox Command: Add

Table: Command: Open

Command: Save

DefaultTableModel modTable;

private void formWindowOpended{

modTable=new DefaultTableModel();

Re-compiled by: Mr. HIEENG Sokh Hymns 22

table.setModel(modTable);

modTable.addColumn(“First Name”);

modTable.addColumn(“Last Name”);

modTable.addColumn(“Date of Birth”);

modTable.addColumn(“Country”);

}

private void cmdAddActionPerformed{

String st[]=new String[4];

st[0\]=txtFirst.getText().trim();

st[0\]=txtLast.getText().trim();

st[0\]=txtDate.getText().trim();

st[0\]=(String)comboCountry.getSelectedItem();

st[3]=st[3].trim();

modTable.addRow(st);

}

private void cmdOpenedActionPerformed{

String st[]=new String[4];

st[0\]=txtFirst.getText().trim();

st[0\]=txtLast.getText().trim();

st[0\]=txtDate.getText().trim();

st[0\]=(String)comboCountry.getSelectedItem();

st[3]=st[3].trim();

modTable.addRow(st);

}

30 – July – 2011

5. Write and Read Object File

5.1. Write and Read Object Fileវែើមបី Write Object ចូល File វយើងរែូវការ Interface មួយវៅ ថា Serializable ដែលសថិែវៅកនុង package java.io.Serializable ដែលមានែួ ទីផទុក Address របស់ Object និងរែូវការ class មួយវទៀែវៅថា ObjectOutputStream ដែលសថិែ វៅកនុង package java.io.ObjectOutputStream ដែលមានែួ ទី Write Object ចូល File ។ Object ដែលរែូវ Write ចូល File រែូវវកើែវចញពី class ដែល implement ជាមួយនឹង Interface Serializable ។

Re-compiled by: Mr. HIEENG Sokh Hymns 23

package TestFile.Sub;

import java.io.Serializable;

public class Data implements Serializable{

public String name;

public int age;

public String address;

public Data(String name; int age; String address){

this.name=name;

this.age=age;

this.address=address;

}

}

packge TestFile.Sub;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.ObjectOutputStream;

public class WriteObject{

public static void main(String arg[]){

try{

File f=new File(“Mydatabase.sys”);

FileOutputStream fo=new FileOutputStream(f);

BufferedOutputStream bo=new BufferedOutputStream(fo);

ObjecOutputStream objO=new ObjectOutputStream(bo);

Data obj;

obj=new Data(“Mam Phanavuth”,30, “PP”);

objO.writeObject(obj);

objO.close();

bo.close();

fo.close();

}catch(Exception e){

System.out.println(e);

}

Re-compiled by: Mr. HIEENG Sokh Hymns 24

}

}

5.2. Read Object From Fileវែើមបី Read Object ពី File វយើងចំបាច់រែូវការ Interface មួយ វ ម្ ោះថា Serializable ដែលសថិែវៅកនុង package java.io.Serializable ដែលមានែួ ទីផទុក Address របស់ object វហើយវារែូវាការ class មួយវទៀែវ ម្ ោះថា ObjectInputStream មាន ែួ ទី Read Object ពី File ។ Object ដែលទទួលទិននន័យពី File ចំបាច់រែូវវកើែវចញពី class រមួគ្នន ជាមួយ Object ដែលបាន Write ចូល File ។

packge TestFile.Sub;

import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.ObjectInputStream;

public class ReadObject{

public static void main(String arg[]){

try{

File f=new File(“Mydatabase.sys”);

FileInputStream fi=new FileInputStream(f);

BufferedInputStream bi=new BufferedInputStream(fi);

ObjecInputStream objI=new ObjectInputStream(bi);

Data obj;

obj=(Data)objI.readObject();

System.out.println(“Name = ”+obj.name);

System.out.println(“Age = ”+obj.age);

System.out.println(“Address = ”+obj.address);

}catch(Exception e){

System.out.println(e);

}

}

}

SH5_Create_bat_and_Run.wmv

public class WriteRead{

public static void main(String arg[]){

try{

Re-compiled by: Mr. HIEENG Sokh Hymns 25

Runtime obj=Runtime.getRuntime();

// obj.exec(“pathProgram pathFile”);

// obj.exec(“\“C:\\Program Files\\Windows Media

Player\\wmplayer.exe\”\“D:\\Song\\Town Vol 09\\AutoRun.bat\” ”);

obj.exec(“C:\\Windows\\explorer.exe\“D:\\Java

2011\\SH5\\AutoRun.bat\” ”)

}catch(Exception e){}

}

}

The End !

Re-compiled by: Mr. HIEENG Sokh Hymns 26

13 – August – 2011

Chapter 10

Swing

1. What is swing?

Swing រឺជាបណតុំ Components ជាវរចើន ដែលវរបើសំរាប់កសាង User Interface ។ ឧទាហរណ៍៖ JFrame, JButton, JTextField, JLabel, JList, JComboBox,

2. How to create JFrame

import javax.swing.WindowConstants;

public class Swing1{

public class Swing1(){

frame=new JFrame();

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

frame.setLayout(NULL);

frame.setSize(800, 600);

cmdOK=new JButton(“OK”);

cmdOK.setBounds(10, 20, 100, 25);

frame.getContentPane().add(cmdOK);

cmdOK.AddActionListener(new ActionListener(){

public void actionPerformed(ActionEvent evt){

cmdOKActionPerformed(evt);

}

});

Frame.setVisible(true);

}

private void cmdOKActionPerformed(ActionEvent evt){

JOptionPane.showMessageDialog(frame, “HI”);

}

public static void main(String arg[]){

new Swing1();

Re-compiled by: Mr. HIEENG Sokh Hymns 27

}

private JFrame frame;

private JFrame cmdOK;

}

public class Swing2 extends JFrame{

public class Swing2(){

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

setSize(800, 600);

setLayout(NULL);

cmdOK=new JButton(“OK”);

cmdOK.setSize(100, 25);

cmdOK.setLocation(10, 20);

cmdOK.AddActionListener(new ActionListener(){

public void actionPerformed(ActionEvent evt){

cmdOKActionPerformed(evt);

}

});

getContentPane().add(cmdOK);

}

private void cmdOKActionPerformed(ActionEvent evt){

JOptionPane.showMessageDialog(this, “HI”);

}

public static void main(String arg[]){

new Swing2().setVisible(true);

}

private JButton cmdOK;

}

20 – August – 2011

3. How to customize JFrame

// Please, see detail “SH5 how to customize JFrame.wmv”

public class SubFrame extends JFrame{

public SubJFrame(){

addWindowListener(new WindowAdapter (){

Re-compiled by: Mr. HIEENG Sokh Hymns 28

formwindowClosing(e);

}

public void windowOpened(WindowEvent e){

formwindowOpened(evt);

}

});

}

private void formwindowOpened(WindowEvent evt){

Dimension ds=java.awt.Toolkit.getDefaultToolkit().getScreenSize();

SetLocation((ds.width-this.getWidth())/2,(ds.height-this.getHeight())/2);

}

Private void formwindowClosing(WindowEvent evt){

int click;

click=JOptionPane.showConfirmDialog(this, “Do you want to Exit?” “Confirm”,

JOptionPane.YES_NO_OPTION);

if(click==JOptionPane.YES_OPTION){

closeMyFrame();

System.exit(0);

}

}

Public void closeMyFrame(){

// Please, override in your own JFrame

}

4. How to customize DefaultTableModel

// Please, see the detail “SH5 how to customize DefaultTableModel.wmv”

public class SubDefaultTableModel extends DefaultTableModel{

public void removeAllRows(){

while (getRowCount()>0){

removeRow(0);

}

}

public void removeSelectedValues(JTable table){

int index[];

index=table.getSelectedRows();

Re-compiled by: Mr. HIEENG Sokh Hymns 29

int j=0;

for(int i=0; i<index.lenght; i++){

removeRow(index[i]-j);

j++;

}

}

private boolean b=false;

public Boolean isCellEditable(int r, int c){

return b;

}

public void setCellEditable(int r, int c){

this.b=b;

}

public boolean isCellEditable(){

return b;

}

}

5. JTable

Create ListSelectionChange of JTable

// Please, see detail “SH5 how to create Enevt Selection JTable.wmv”

table.getSelectionModel().addListSelectionListener (new ListSelectionListener(){

public void valueChange(ListSelectionEvent e){

tableListSelectionChanged(e);

}

});

private void tableListSelectionChanged(ListSelectionEvent evt){

// Execute when selection has been changed.

}

03 – September – 2011

Create Event columnSelectionChanged of JTable

// Please, see detail “SH5 create Row and ColumnSelectionChange.wmv”

Table.getColumnModel().addColumnModelListener(new TableColumnModelLIstener(){

public void columnAdded(TableColumnModelEvent e){

Re-compiled by: Mr. HIEENG Sokh Hymns 30

// Throw new unsupportedOperationException (“Not support yet.”);

}

public void columnRemoved(TableColumnModelEvent e){

//Throw new unsupportedOperationException (“Not support yet.”);

}

public void columnMoved(TableColumnModelEvent e){

//Throw new unsupportedOperationException (“Not support yet.”);

}

public void columnMarginChanged(ChangeEvent e){

//Throw new unsupportedOperationException (“Not support yet.”);

}

public void columnSelectionChanged(ListSelectionEvent e){

tableColumnSelectionChanged(e);

//Throw new unsupportedOperationException (“Not support yet.”);

}

});

private void tableColumnSelectionChanged(ListSelectionEvent evt){

// Execute when column has been changed.

}

Use JTextField, JComboBox, JCheckBox as the cell of JTable

table.getColumnModel().getColumn(int col).setCellEditor(newDefaultCellEditor

(Component)); ជា Method មួយមានែួ ទី Add Components ែូចជា JTextField,

JComboBox, JCheckBox វធវើជា Cell របស់ JTable។

Resize column of JTable

Table.getColumnModel().getColumn(int col).setPreferedWidth(int width); ជា Method មាន ែួ ទីកំណែ់ទំហំរបស់ Column ដែលសថិែវៅកនុង index ណាមួយនន Table ។

10 – September – 2011

How to Customize JTable

Set all TableHeader of JTables

try{

UIManager.getLookAndFeelDefaults().put(“TableHeader.background”,new

color(136,136,136));

Re-compiled by: Mr. HIEENG Sokh Hymns 31

UIManager.getLookAndFeelDefaults().put(“TableHeader.foreground”,new

color(0,0,0));

UIManager.getLookAndFeelDefaults().put(“TableHeader.font”,new

font(“Arial”,font.BOLD,12));

}catch(Exception e){}

Using JTableHeader

table.getTableHeader().setBackground(color.red);

table.getTableHeader().setFont(new Font(“Arial”,Font.BOLD,14));

table.getTableHeader().setForeground(color.YELLOW);

How to resize height of TableHeader

table.getTableHeader().setPreferedSize(new Dimension(sp.getWidth(),18));

// sp is the JScrollPane

Date and Calendar (abstract)ជា class ដែលសថិែវៅកនុង Package Java.util.Date មានែួ ទី ផទុកកាលបរវិចឆទទំាងអែីែកាល បចចុបបនន និងអ រែ។ Calendar ជា abstract class

ដែលសថិែវៅកនុង Package java.util.calendar មានែួ ទីទទួលយកពែ៌មានទំាងអស់របស់ កាលបរវិចឆទ។

How to use Date

EX:

Date date=new Date();

String st= “ ”+date;

System.out.println(st);

// Sat Sept 10.18.22:17 ICT 2011

EX:

SimpleDateFormat sdf=new SimpleDateFormat(“EEE,dd/MMMM/yyy”);

String st=sdf.format(date);

System.out.println(st);

// Saturday, 10/September/2011

Re-compiled by: Mr. HIEENG Sokh Hymns 32

EX:

long time

time=system.currentTimeMillis();

string st=sdf.format(time);

system.out.println(st);

// Saturday, 10/September/2011

How to calculate Date

EX:

long millis1=system.currentTimeMillis();

try{

thread.sleep(5000);

}catch(Exception e){}

Long mills2=system.currentTimeMillis();

long millis;

millis=millis2-millis1;

system.out.println(millis);

EX:

Date dataOld=new Date();

long milli;

milli=dateOld.getTime();

long add;

add=2*24*60*60*1000;

milli+=add;

Date dateNew=new Date();

dateNew.setTime(milli);

System.out.println(dataNew);

Re-compiled by: Mr. HIEENG Sokh Hymns 33

Using Calendar to control on Date

EX:

calendar cd=calendar.getInstance();

cd.setTime(New Data());

// cd.setTimeInMillis(System.currentTimeMillis());

int day,month,year;

day=cd.get(cd.DAY_OF_MONTH);

month=cd.get(cd.MONTH)+1;

year=cd.get(cd.YEAR);

system.out.println(day+“/”+month “/”+year);

EX:

calendar cd=calendar.getInstance();

int day=5;

int month=8; // September

int year=2011;

cd.set(year,month,day);

Date date=new Date();

Date=cd.getTime();

SimpleDateFormat sdf=new SimpleDateFormat(“EEEE,dd/MMMM/yyyy”);

System.out.println(sdf.format(date));

EX:

calendar cd=calendar.getInstance();

int year=2011;

int month=7; // index of month start from 0 to 11.

Int date=10; // date can start from 1 to 20, 29, 30 or 31.

cd.set(year,month,day);

int dayofweek=cd.get(cd.DAY_OF_WEEK);

// Sunday=1, Monday=2,…,Saturday=7

Int maxDayOfMonth;

maxDayOfMonth=cd.getActualMaximum(cd.DAY_OF_MONTH);

system.out.println(“Maximum of Day in a month”+maxDayOfMonth);

Re-compiled by: Mr. HIEENG Sokh Hymns 34

The End !