You are on page 1of 34

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


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

int numItems;

Item ComboBox

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


String item;
item = (String) combo.getSelectedItem();
Object getItemAt(int); method
Index

Item

String item;
item = (String) combo.getItemAt(3);
void addItem(object); method

add Item ComboBox

String item;
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

Item

ComboBox

String item;
Re-compiled by: Mr. HIEENG Sokh Hymns

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:

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
}
Re-compiled by: Mr. HIEENG Sokh Hymns

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 (2 nd)

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

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; cant use private
b = 1;
c = 1;
d = 1;
}
}
Same package noSubClass (3 rd)
public class NoSubAccess{
publicNoSubAccess(){
Access obj = new Access();
// obj.a = 1; cant use private
obj.b = 1;
obj.c = 1;
obj.d = 1;
}
}
Re-compiled by: Mr. HIEENG Sokh Hymns

Different package SubClass (4th)


import accessControl.Access;
public class DiffSubAccess extends Access{
public DiffSubAccess(){
// a = 1; cant use private
// b = 1; cant use NoModifier
c = 1;
d = 1;
}
}
Different package noSubClass (5 th)
import accessControl.Access;
public class DiffNoSubAccess{
public DiffNoSubAccess(){
Access obj = new Access();
// obj.a = 1; cant use private
// obj.b = 1; cant use NoModidier
// obj.c = 1; cant 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


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

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

First Name:
Last Name:
Gender
Male

Female

Country
First Name

ComboBox
Last Name Gender

Add

Country

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);
}
}

Re-compiled by: Mr. HIEENG Sokh Hymns

10

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; cant create Normal instanceVariable
// public void show();
// public void showValues(){
cant create Normal Method
}
}

Re-compiled by: Mr. HIEENG Sokh Hymns

11

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

12

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

13

}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

14

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

15

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

16

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(Cant 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

17

}
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

18

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

Re-compiled by: Mr. HIEENG Sokh Hymns

19

Write File

*.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(Im well.\r\n);
fw.close();
}catch(Exception e){}
Re-compiled by: Mr. HIEENG Sokh Hymns

20

}
}
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:
Last Name:
Date of Birth:
Country:
Table:

TextField
TextField
TextField
ComboBox

Command: Add
Command: Open
Command: Save

DefaultTableModel modTable;
private void formWindowOpended{
modTable=new DefaultTableModel();
Re-compiled by: Mr. HIEENG Sokh Hymns

21

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

22

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

23

}
}
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

24

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

25

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

26

}
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

27

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

28

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

29

// 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

30

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

31

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

32

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

33

The End !

Re-compiled by: Mr. HIEENG Sokh Hymns

34

You might also like