Download Chapter 7 Packages and Interfaces

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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
1
ចំណំ៖
យយើងអាចយក 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 មានែួ
វ្ចើនបំសុែ ដែល្ែូេបានបង្ហាញវៅកនុង Drop-down List ។
ឧទាហរណ៍៖
combo.setMaximumRowCount(5);
 int getItemCount(); ជា method ម្ួ យមានែួ
ឧទាហរណ៍៖
int numItems;
ទីកំណែ់ចំនួន
Item
ទីរាប់ចំនួន Item មានកនុង ComboBox ។
numItems = combo.getItemCount();
// get numbers of Items in JComboBox
 void setSelectedIndex(int); ជា method ម្ួ យមានែួ
តាម្ Index ដែលវយើងបានកំណែ់។
ឧទាហរណ៍៖
combo.setSelectedIndex(3);
ទីបវងក ើែការ Select Item ណាម្ួ យ
 Object getSelectedItem();ជា method ម្ួ យមានែួ
Select ។
ឧទាហរណ៍៖
String item;
ទីទាញយក Item ដែល User បាន
item = (String) combo.getSelectedItem();
 Object getItemAt(int); ជា method ម្ួ យមានែួ
Index ណាម្ួ យ។
ឧទាហរណ៍៖
String item;
Re-compiled by: Mr. HIEENG Sokh Hymns
ទីទាញយក Item ដែលសថ ិែវៅកនុង
2
item = (String) combo.getItemAt(3);
 void addItem(object); ជា method ម្ួ យមានែួ
ឧទាហរណ៍៖
String item;
ទី add Item ចូ ល ComboBox ។
item = “Teacher”;
combo.addItem(item);
combo.addItem(“Student”);
txtAdd
cmdAdd
combo
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 ម្ួ យមានែួ
ComboBox។
ឧទាហរណ៍៖
String item;
ទី្បវ្រៀែ Item ថ្មីចូលកនុង
item = “New Item”;
combo.insertItemAtt(item, 3);
 void removeItemAt(int);
 void removeItem(object);
 void removeAllItems();
ឧទាហរណ៍៖
combo.removeItemAt(3);
combo.removeItem(“Student”);
Re-compiled by: Mr. HIEENG Sokh Hymns
3
combo.removeAllItems();
Homework:
ចូ រសរវសរ Program វែើម្បី Add ទិននន័យចូ លកនុង ComboBox ។ ទិននន័យដែល្ែូេបាន Add
្ែូេវរៀបតាម្លំោប់វោយសវ ័យ្បេែត ិ (A → Z) ។ ម្ិនអនុញ្ជាែឲ្យទិននន័យ្ចំដែល ឬទវទ វៅកនុង
ComboBox វទ។
Correction:
TextField
CammandAdd
ComboBox
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
}
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)
Re-compiled by: Mr. HIEENG Sokh Hymns
4
25 – June – 2011
1.3. Inheritance with 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)
ឧទាហរណ៍អំពី 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;
Re-compiled by: Mr. HIEENG Sokh Hymns
5
}
}
ឧទាហរណ៍អំពី 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;
}
}
ឧទាហរណ៍អំពី 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{
Re-compiled by: Mr. HIEENG Sokh Hymns
6
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);
}
ឧទាហរណ៍៖
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();
}
Re-compiled by: Mr. HIEENG Sokh Hymns
7
 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);
}
}
 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();
}
}
Re-compiled by: Mr. HIEENG Sokh Hymns
8

JRadioButton ជា class ដែលសថ ិែវៅកនុង Package Javax.swing.JRadioButton ។ class
JRadioButton ជា Components ដែលអនុញ្ជាែិឲ្យ Users វ្រើសវរ ើស Option ណាម្ួ យ
ដែលពួ កវរចង់បាន។
ឧទាហរណ៍៖
JRadioButton radio = new JRadioButton();
កនុង class JRadioButton មាន method 2 ដែលសំខាន់៖
 void setSelected(Boolean); ជា method ដែលមានែួ
RadioButton ។
ឧទាហរណ៍៖
Radio.setSelected(true);
 boolean isSelected();ជា method
Button្ែូេបាន Select ឬអែ់។
ឧទាហរណ៍៖
if(radio.isSelected()){
ដែលមានែួ
ទីបវងក ើែ Select ឲ្យ
ទីវសទៀងផ្ទទែ់វម្ើលថាRadio
// radio has selected
}else{
// radio has not selected
}
First Name:
សLast Name:
Gender
Male
Country
First Name
Female
ComboBox
Last Name Gender
Re-compiled by: Mr. HIEENG Sokh Hymns
Add
Country
9
Homework:
ចូ រសរវសរ Program វែើម្បី input ទិននន័យែូ ចរ ូបខាងវលើ វហើយទិនននយ
័ ដែល User
បញ្ចល
ូ ្ែូេធ្លាក់ចុលកនុង Text area វៅវពល User click button Add ។
2.3. Multi Inheritance with Interface
package Interface;
public class SubInter implements Inter1, Inter2{
public void showA(){
System.out.println(VALUES_A);
}
public void showB(){
System.out.println(VALUES_B);
}
}
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 “extends” ។
 វបើ interface ទទួ លម្រែកពី interface វយើងចំបាច់វ្បើ Keyword “extends” ។
 វបើ class ទទួ លម្រែកពី interface វយើងចំបាប់វ្ចើ Keyword “implements” ។
សង្ខេប៖
 class extends class
 interface extends interface
 class implements interface
 interface ??? class
Re-compiled by: Mr. HIEENG Sokh Hymns
10
Interface ម្ិនអាចទទួ ល Member ពី Class បានវទ វោយសារដែវៅកនុង class មាន
Normal instanceVariable និង Normal Method ។
2.4. Interface 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
}
}
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 !
The three OOP Principles (Object Oriented Programming) ៖ ពាកយថា OOP មានន័យថា
Object Oriented Programming ។ វែើម្បីសំគ្នល់ថា Program ម្ួ យមានលកខ ណៈជា OOP លុោះ ្តាដែ
Program វ ោះ្ែូេបំវពញលកខ ណៈពិវសស ៣យ៉ាងរឺ៖ Encapsulation, Inheritance និង
Polymorphism ។
 Encapsulation ៖ ជាការវេចខ្ច ប់ទិននន័យវោយមានសុេែថ ិភាព មានន័យថា Instance
variable របស់ Class វយើងម្ិនឲ្យវរ Access វោយផ្ទទល់បានវទ វយើងឲ្យវរ Access តាម្
Method ។
 Inheritance ៖ ជាការវសទរ Member ពី Class ម្ួ យវៅកាន់ Class ម្ួ យវសេងវទៀែដែលវធវ ើ
ឲ្យមានលកខ ណៈង្ហយ្សួ ល ម្ិនខាែវពលសរវសរ Code ្ចំដែលវ ើង េ ិញ។
 Polymorphism ៖ ជាការបវងក ើែ Class រំរ ូ វហើយវយើងអាចយក Class វ ោះវៅដកច្ចន
បាន Class វ្ចើនវទៀែដែលមានលកខ ណៈ្សវែៀងគ្នន។
Re-compiled by: Mr. HIEENG Sokh Hymns
11
Chapter 8
Exception Handling
1. The Exception Hierarchy
កនុងភាសា Java វយើងមាន code សំរាប់សរវសរ error ដែវបើវៅដែមាន error វយើងអាចបំ
បាែ់ error ទា ំងអស់វ ោះបាន។
Class Throwable មានែួ ទី្រប់្រង្រប់ error ទា ំងអស់ដែលវកើែមានវ ើង។ error ទា ំង
វ ោះដចកវចញជាពីរ៖
 Exception

ArithmeticException

NumberFormatException

ArrayIndexOutOfBoundsException

ArrayStroeException
Re-compiled by: Mr. HIEENG Sokh Hymns
12

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
}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());
Re-compiled by: Mr. HIEENG Sokh Hymns
13
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 !
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
Re-compiled by: Mr. HIEENG Sokh Hymns
14
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 មានែួ
directory ។
ឧទាហរណ៍៖
String parentF, parentD;
ទីទទួ លយក្ែឹម្ដែ address របស់ file ឬ
parentF=objF.getParent (); // parentF= “C:/myPro/My File”
parentD=objD.getParent (); // parentD= “C:/myPro”
09 – July – 2011
 String getPath();ជា method មានែួ
Directory
ឧទាហរណ៍៖
String pathF, pathD;
ទីទទួ លយកទា ំង Address និងវ្មោះ របស់ File ឬ
pathF=objF.getPath (); // pathF= “C:/myPro/My File/text.txt”
pathD=objD.getPath (); // pathD = “C:/myPro/My File”
 String getAbsolutePath();ជា method មានែួ
Method getPath ។
ឧទាហរណ៍៖
File objF=new File(“My File/text.txt”);
ទីទទួ លយក Path បានជាក់ចាស់ជាង
String path,abPath;
Path=objF.getPath(); // path=“My File/text.txt”
abPath()=objF.getAbsolutePath(); // abPath=“C:/myPro/My File/text.txt”
 String getCanocicalPath(); ជា method មានែួ
getAbsolutePath ។
ឧទាហរណ៍៖
File objF=new File(“../text.txt”);
ទីទទួ លយកPath បានជាក់ចាស់ជាង
String abPath, canPath;
abPath=objF.getAbsolutePath(); // “c:/MyPro/../text.txt”
Re-compiled by: Mr. HIEENG Sokh Hymns
15
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”);
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.”);
Re-compiled by: Mr. HIEENG Sokh Hymns
16
 boolean isFile();ជា method មានែួ ទីវសទៀងផ្ទទែ់វម្ើល ថាវែើ object វ
File ឬក៏ម្ិនដម្ន? វបើជា object fileវា Return true ។
ឧទាហរណ៍៖
File objF=new File(“C:/myPro/My File/text.txt”);
ោះជា obj របស់
if(objF.isFile())
System.out.println(“This is file.”);
else{
System.out.println(“This is not file.”);
}
 boolean isDirectory(); ជា method មានែួ ទីវសទៀងផ្ទទែ់វម្ើល ថាវែើ object វ
របស់ File ឬក៏ម្ិនដម្ន? វបើជា object directory វា Return true ។
ឧទាហរណ៍៖
File objD=new File(“C:/myPro/My File”);
ោះជា obj
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 មានែួ ទីបង្ហាញ Name របស់ 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 មានែួ
ដែលសថ ិែ វៅកនុងទីតាំងណាម្ួ យ។
ឧទាហរណ៍៖
File objD=new File(“C:/myPro”);
Re-compiled by: Mr. HIEENG Sokh Hymns
ទីទាញយក Object Directory និង Object File
17
File f[];
f=objD.listFiles();
for(int i=0; i<f.length; i++)
f[i].delete();
 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 ។
*.BufferedOutputStream ជា class ដែលសថ ិែវៅកនុង Package java.io.BufferedOutputStream
មានែួ ទីបវងក ើែទីតាំងបំរុងទុកសំរាប់ Write ទិននន័យចូ ល File ។
Re-compiled by: Mr. HIEENG Sokh Hymns
18
*.PrintStream ជា class ដែលសថ ិែវៅកនុង Package java.io.PrintStream មានែួ
ជា String ចូ លកនុង File ។
ឧទាហរណ៍៖ How to Write File.wmv
public class WriteRead{
ទីអាច Write
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 វហើយវាម្ិនចំបាច់្ែូេការ FileOutputStream និង 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){}
}
}
How to Write and Read 1 Record.wmv
Label: Name
TextField
Label: Age
TextField
Re-compiled by: Mr. HIEENG Sokh Hymns
19
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){}
}
}
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 ។
package TestFile.Sub;
import java.io.Serializable;
public class Data implements Serializable{
public String name;
Re-compiled by: Mr. HIEENG Sokh Hymns
20
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);
}
}
}
5.2. Read Object From Fileវែើម្បី Read Object ពី File វយើងចំបាច់្ែូេការ Interface ម្ួ យ
វ្មោះថា Serializable ដែលសថ ិែវៅកនុង package java.io.Serializable ដែលមានែួ ទីសទក
ុ
Address របស់ object វហើយវា្ែូវាការ class ម្ួ យវទៀែវ្មោះថា ObjectInputStream មាន
Re-compiled by: Mr. HIEENG Sokh Hymns
21
ែួ ទី 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{
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\” ”)
Re-compiled by: Mr. HIEENG Sokh Hymns
22
}catch(Exception e){}
}
}
The End !
13 – August – 2011
Chapter 10
Re-compiled by: Mr. HIEENG Sokh Hymns
23
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();
}
private JFrame frame;
private JFrame cmdOK;
}
public class Swing2 extends JFrame{
Re-compiled by: Mr. HIEENG Sokh Hymns
24
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 (){
formwindowClosing(e);
}
public void windowOpened(WindowEvent e){
formwindowOpened(evt);
}
});
Re-compiled by: Mr. HIEENG Sokh Hymns
25
}
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();
int j=0;
for(int i=0; i<index.lenght; i++){
removeRow(index[i]-j);
j++;
}
}
Re-compiled by: Mr. HIEENG Sokh Hymns
26
private boolean b=false;
public Boolean isCellEditable(int r, int c){
return b;
}
public void setCellEditable(boolean b){
this.b=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){
// 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){
Re-compiled by: Mr. HIEENG Sokh Hymns
27
//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));
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);
Re-compiled by: Mr. HIEENG Sokh Hymns
28
 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
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{
Re-compiled by: Mr. HIEENG Sokh Hymns
29
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);
 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);
Re-compiled by: Mr. HIEENG Sokh Hymns
30
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);
The End !
Re-compiled by: Mr. HIEENG Sokh Hymns
31
Related documents