Professional Documents
Culture Documents
Java Programming Part 2
Java Programming Part 2
package p1;
class Simple{
int a;
int b;
}
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();
}
}
class package
1. keyword import Header file C C++
class
package
2. keyword import
package
class
combo.setEditable(true);
void setMaximumRowCount(int); method
Item
Drop-down List
combo.setMaximumRowCount(5);
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
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
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;
}
NoModifier
Protected
Public
Same class
yes
yes
yes
yes (1st)
no
yes
yes
yes (2 nd)
no
yes
yes
yes (3rd)
no
no
yes
yes (4th)
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;
}
}
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
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();
}
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);
}
}
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();
}
}
Option
Select
RadioButton
Radio.setSelected(true);
boolean
isSelected();
method
Radio
Button Select
if(radio.isSelected()){
// radio has selected
}else{
// radio has not selected
}
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);
}
}
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
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 !
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
Out of memory
Not found hard disk
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
}
The End !
Re-compiled by: Mr. HIEENG Sokh Hymns
14
09 July 2011
Chapter 9
java.io.File
file directory
Form:
file directory
file directory
address file
directory
15
Address File
Directory
Path
Method getPath
Path
getAbsolutePath
16
objD.mkdirs();
boolean createNewFile(); method
Directory File
? Return true
delete
object
obj
17
}
boolean isDirectory(); method
object
obj
18
File byte
Drive
byte
long getUsableSpace(); method
Space Drive
byte
23 July 2011
3. FileInputStream class Package java.io.FileInputStream
Read
File
Read
19
Write File
Write File
Write
String File
Write
20
}
}
How to Write and Read 1 Record.wmv
Label: Name
TextField
Label: Age
TextField
Address
TextField
Command Save
Command Open
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
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
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 !
25
13 August 2011
Chapter 10
Swing
1. What is swing?
Swing Components User Interface
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
}
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
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
How to use Date
EX:
EX:
SimpleDateFormat sdf=new SimpleDateFormat(EEE,dd/MMMM/yyy);
String st=sdf.format(date);
System.out.println(st);
// Saturday, 10/September/2011
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;
32
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 !
34