alllessons
Document Sample


-1- (Java Notes 2003-4 Bar Ilan University)
Java Notes for “Programming Languages” and -Comments //… or /*…*/ or /**…*/
“Advanced Programming” -Blocks {…}
-Methods
Course URLs: http://www.cs.biu.ac.il/~hasonz -main method (always public static void)
http://www.cs.biu.ac.il/~akivan/APCourse.html -Identifiers (UpperCase, LowerCase, _, $, Digits) cannot start with digit
old Course URLs: http://www.cs.biu.ac.il/~luryar case sensitive (TOTAL, Total, total)
http://www.cs.biu.ac.il/~linraz -Consistency in naming (Beginning Lowercase => methods and identifiers
Beginning Uppercase => classes
Java Source
Across the All Uppercase => constants
Code (.java) Internet -print and println methods
using -command line arguments (main method)
HT ML
-object oriented programming (classes, objects, inheritance, etc.)
Java
Java Bytecode
Compiler
(.class)
Web Browser //Turkey.java File
class Turkey
{
Java Bytecode Java
Interpreter Compiler
public static void main(String[] args)
Interpreter
{
System.out.print("The international "
(Applet) + "dialing code ");
Machine System.out.print("for Turkey is " + 90);
Code (.exe) }
}
//FrstProg.java file //NameTag.java File
class FrstProg class NameTag
{ {
/*This program just writes something to the console public static void main(String[] args)
and will stop executing*/ {
public static void main(String[] args) System.out.println("Hello! My name is " +
{ args[0]);
System.out.println("This is the first lesson"); }
//println is part of API }
}
} javac NameTag.java (compile)
HOW TO COMPILE AND RUN JAVA FILES:
java NameTag XXX (run)
Hello! My name is XXX (output)
Java Compiler:
javac FrstProg.java (creates FrstProg.class) To import a package:
Java Interpreter:
java FrstProg (executes FrstProg.class) import package.class;
Or:
Output: import package.*;
This is the first lesson
-2- (Java Notes 2003-4 Bar Ilan University)
JAVA API (Application Programming Interface) OPERATORS:
Unary: + -
View: http://java.sun.com/j2se/1.3/docs/api/ Binary: * / % Multiplication, div ision, remainder
Download: http://java.sun.com/j2se/1.3/docs.html + - Addition, subtraction
+ String concatenation
= Assignment
Packages += -= *= /= %=
java.applet creates programs (applets) that are easily transported across
the web. count++ return count and then add 1
java.awt (Abstract Windowing Toolkit) Draw graphics and create ++count add 1 and then return count
graphical user interfaces. count-- return count and then subtract 1
java.io perform a wide variety of I/O functions. --count subtract 1 and then return count
java.lang general support. It is automatically imported.
java.math for high precision calculations. ! Logical not ^ Bitwise xor == !=
java.net communicate across a network. && Logical and & Bit wise and > <
java.rmi (Remote Method Invocation) create programs that can be || Logical or | Bit wise or >= <=
distributed across multip le co mputers.
java.sql interact with databases.
java.text format text for output. CODITIONS AND LOOPS:
java.util general utilities. condition ? expression1 : exp ression2
example: int larger = (nu m1>nu m2) ? num1 : nu m2 ;
PRIMITIVE DATA TYPES:
byte 8 bits -128 127 if (condition) switch (expression) {
short 16 bits -32768 32767 Statement1 case value1:
int 32 bits -2 b illion 2 billion else Statement-list1; break;
long 64 bits -1019 1019 Statement2 case value2:
Statement-list2; break;
Floating point: ….
float 32 bits defau lt:
double 64 b its Statement-list3;
}
Others:
char 16 bits 65536 Un icode characters while (condition) do Statement for (init; cond; incr)
boolean false true Statement; while (condition); Statement;
void
continue break return
WRAPPER CLASS ES:
Classes declared in package java.lang:
Byte Float Character Boolean Vo id
Short Double
Integer
Long
-3- (Java Notes 2003-4 Bar Ilan University)
INSTANTIATION AND REFER ENCES GARBAGE COLLECTION
class CarExample Objects are deleted when there are no mo re references to them. There is a possibility
{ to have the System run the garbage collector upon demand using the System.gc()
public static void main(String[] args) method.
{ Calling the gc() method suggests that the Java Virtual Machine expend effort toward
int total = 25; recycling unused objects in order to make the memo ry they currently occupy
int average; available
average = 20; for quick reuse. When control returns from the method call, the Java Virtual Machine
has made a best effort to reclaim space fro m all d iscarded objects.
//CarClass should be declared
CarClass myCar = new CarClass();
CarClass yourCar;
yourCar = new CarClass(); If we add the line:
//To call a method use "." CarClass momCar = myCar;
myCar.speed(50);
yourCar.speed(80);
we get the following drawing:
System.out.println("My car cost $" + myCar.cost());
}
}
class CarClass _speed = 50 _speed = 80
{ myCar yourCar
int _speed;
int _cost;
CarClass() 2 1
{
_speed = 0;
_cost = 2500;
}
public void speed(int speed)
{
To reduce the number of references to an object,
_speed = speed; We do the following:
}
MyCar = null;
public int cost()
{ (What would happen in C++ if we do this???)
return _cost;
}
}
-4- (Java Notes 2003-4 Bar Ilan University)
STRINGS: OUTPUT:
class StringExample str1: Seize the day Index of 'e' in str4: 9
{ str2: Char at pos 3 in str1: z
public static void main (String[] args) str3: Seize the day Substring 6 to 8 of str1: th
{ str4: Day of the str1 and str5 refer to the same object
String str1 = "Seize the day";
seize str1 and str3 don't refer to the same
String str2 = new String();
String str3 = new String(str1); str5: Seize the day object
String str4 = "Day of the seize"; str1 and str3 contain the same chars
String str5 = "Seize the day"; length of str1 is 13
System.out.println("str1: " + str1); length of str2 is 0 str2 now is: SEIZE THE DA Y
System.out.println("str2: " + str2); str5 is now: SXizX thX day
System.out.println("str3: " + str3); str1 and str5 don't refer to the same object
System.out.println("str4: " + str4);
System.out.println("str5: " + str5);
System.out.println();
System.out.println("length of str1 is " + str1.length()); Useful methods for string:
System.out.println("length of str2 is " + str2.length()); length() :returns the length
System.out.println(); charAt (int index) :returns char at that positions (0..)
System.out.println("Index of 'e' in str4: " indexOf(char ch) :returns index (0..) of first occurrence
+ str4.indexOf('e')); lastindexOf(char ch) :returns index (0..) of last occurrence
System.out.println("Char at pos 3 in str1: "
+ str1.charAt(3));
endsWith(String suffix) :returns true if has this suffix
System.out.println("Substring 6 to 8 of str1: " startsWith(String prefix) :returns true if has this prefix
+ str1.substring(6,8)); equals(Object obj) :returns true if two strings are the same
if (str1==str5) equalsIgnoreCase(Object obj) :returns true if two strings are equal, ignoring case
System.out.println("str1 and str5 refer to the “ toLowerCase() :returns a new string of lower case
+ “same object"); toUpperCase() :returns a new string of upper case
if (str1 != str3) substring(int begin, int end) :returns a new string that is a substring of this string
System.out.println("str1 and str3 don't refer to “ including begin, excluding end.
+ “the same object");
if (str1.equals(str3))
System.out.println("str1 and str3 contain the “ java.lang.StringBuffer.
+ ”same chars");
System.out.println(); StringBuffer- implements a mutable sequence of characters.
str2 = str1.toUpperCase(); String - implements a constant sequence of characters.
System.out.println("str2 now is: " + str2);
str5 = str1.replace('e','X');
System.out.println("str5 is now: " + str5); public class ReverseString{
public static void main(String[] args){
//now check again String source="abcdefg";
if (str1==str5) int strLen=source.length();
System.out.println("str1 and str5 refer to the “ StringBuffer dest = new StringBuffer( strLen );
+ “same object"); for( int i= strLen-1; i>=0; i--){
else System.out.println("str1 and str5 don't refer to “ dest.append( source.charAt(i) );
+ “the same object"); }
} System.out.println( dest );
} }
}
output: gfedcba
-5- (Java Notes 2003-4 Bar Ilan University)
ARRAYS: MULTI DIMENS IONAL ARRAYS:
class ArrayTest class MultiArray
{ {
public static void main(String[] args) int[][] table = {{1,2,3,4},
{ {11,12},
ArrayParameters test = new ArrayParameters();
{21,22,23}};
//first way to initialize array with fixed size and data
int[] list = {11,22,33,44,55};
//second way to initialize array. Fixed size. public void init1()
int[] list2 = new int[5]; //default for int is 0... {
//fill in data table = new int[5][];
for (int i=0; i<list.length; i++) for (int i=0; i<table.length; i++)
{ {
list2[i]=99; table[i] = new int[i];
} }
test.passElement(list[0]); //list: 11 22 33 44 55
}
test.chngElems(list); //list: 11 22 77 44 88
test.chngRef(list, list2); //list: 11 22 77 44 88
test.copyArr(list, list2); //list: 99 99 99 99 99 public void print()
list=test.retRef(list2); //list: 99 66 99 99 99 {
} for (int rows=0; rows<table.length; rows++)
} {
for (int col=0; col<table[rows].length;
class ArrayParameters col++)
{ System.out.print(table[rows][col] + " ");
public void passElement(int num)
//move cursor to next line
{
num = 1234; //no change in original System.out.println();
} }
public void chngElems(int[] my1) //reference passed }
{
my1[2] = 77; public static void main(String[] args)
my1[4] = 88; {
} MultiArray ma = new MultiArray();
public void chngRef(int[] my1, int[] my2) //reference passed ma.print();
{
my1 = my2;
ma.init1();
} ma.print();
public void copyArr(int[] my1, int[] my2) }
{ }
for (int i=0; i<my2.length; i++)
my1[i]=my2[i]; OUTPUT:
} 1234
public int[] retRef(int[] my1) 11 12
{
21 22 23
my1[1] = 66;
return my1;
} 0
} 00
000
0000
-6- (Java Notes 2003-4 Bar Ilan University)
INPUT/ OUTPUT: “Nu mbers.dat” file
1.1
import java.io.*; 2.2
class Greetings
3.3
{ 4.4
public static void main (String[] args) 10.5
{
try
{ javac Su m.java
DataInputStream in = new DataInputStream(System.in); java Su m
System.out.println("What is your name?"); How many numbers: 5
String name = in.readLine(); The total is 21.5
System.out.println("Hello " + name);
}
catch (IOException e) //This program does not use deprecated methods
{ import java.io.*;
System.out.println("Exception: " + e.getMessage());
} class MyTest
} {
} BufferedReader reader = null;
public void read()
What is your name? {
Bill Gates try
Hello Bill Gates {
reader = new BufferedReader (new FileReader
import java.io.*; ("numbers.dat"));
}
class Sum catch (FileNotFoundException f)//if file was not found
{ {
public static void main (String[] args) System.out.println("File was not found");
{ System.exit(0);
try }
{
DataInputStream in = new DataInputStream(System.in); try
DataInputStream fin = new DataInputStream(new {
FileInputStream(“numbers.dat”)); String line= new String();
int count; double sum = 0.0;
double total = 0; while((line=reader.readLine())!=null)
System.out.print(“How many numbers? “); {
System.out.flush(); double d = Double.parseDouble(line);
count = Integer.parseInt(in.readLine()); sum += d;
for (int i=1; i<=count; i++) }
{ System.out.println("Sum is " + sum);
Double number = Double.valueOf(fin.readLine()); }
total += number.doubleValue(); catch (Exception e)
} {
System.out.println(“The total is: “ + total); System.out.println("Exception occurred");
} }
catch (IOException e) }
{
System.out.println(“Exception while performing “ public static void main(String[] args)
+ e.getMessage()); {
} MyTest test = new MyTest();
} test.read();
} }
}
-7- (Java Notes 2003-4 Bar Ilan University)
Class java.io.File java.util.StringTokenizer
import java.io.*; import java.io.*;
import java.util.StringTokenizer;
public class BuildDir
{ public class Tokens
public static void main(String[] args) throws IOException {
{ public static void main(String[] args) throws IOException
File from = new File("source.txt"); {
File newDir = new File("newDir"); BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
File to = new File("newDir/target.txt"); int first,second,pitaron;
int i;
newDir.mkdir(); char sign;
String line;
FileReader in = new FileReader( from ); do
FileWriter out = new FileWriter( to ); {
System.out.println("Enter the exercise with =.");
int character; line = in.readLine();
while( (character=in.read())!= -1 ) StringTokenizer st=new StringTokenizer(line);
{ first=Integer.parseInt( st.nextToken("-+*/") );
out.write(character); sign = ( st.nextToken("1234567890") ).charAt(0);
} second= Integer.parseInt( st.nextToken("=") );
switch(sign)
in.close(); {
out.close(); case '+': pitaron= first+second; break;
case '-': pitaron= first-second; break;
from.delete(); case '*': pitaron= first*second; break;
} case '/': pitaron= first/second; break;
} default : pitaron =0;
}
Useful methods of File System.out.println(line + pitaron);
}
getAbsoulutePath() – return string. Absoulute path of the file. while( pitaron != 0);
}
canRead(),canWrite()-return boolean .app can read/write to file. }
IsFile(), isDirectory()- return boolean. output:
list()- return string[]. The list of the files in the directory. Enter the exercise with =.
12-33=
mkDir() – return boolean. Creat a directory.
12-33=-21
renameTo(File des) –return boolean. Renames the file name to the StringTokenizer(st1,delim)- construct a StringTokenizer for st1. delim= the delimiters.
Des pathname.
StringTokenizer(st1)- construct a StringTokenizer for st1. delimiters= tab,\n,space.(default)
nextToken(delim)- return the string until the delim.
CountTokens()- return the number of tokens, using the current delimiter set.
HasM oreTokens()- return boolean, test if there are more tokens available.
-8- (Java Notes 2003-4 Bar Ilan University)
Class RandomAccessFile
Example:
+--jav a.io.RandomAccessFile import java.io.*;
public class RandomAccessFile public class CopyTwoToOne
{
extends Object
public static void main(String[] args) throws IOException
implements DataOutput, DataInput {
RandomAccessFile in1;
Instances of this class support both reading and writing to a random access file. A random
RandomAccessFile in2;
access file behaves like a large array of bytes stored in the file system. There is a kind of RandomAccessFile out;
cursor, or index into the implied array, called the file pointer; input operations read bytes
in1=new RandomAccessFile("source1.txt","r");
starting at the file pointer and advance the file pointer past the bytes read. If the random out=new RandomAccessFile("target.txt","rw");
access file is created in read/write mode, then output operations are also available; output
byte[] con = new byte[(int)in1.length()];
operations write bytes starting at the file pointer and advance the file pointer past the bytes in1.readFully(con);
out.write(con);
written. Output operations that write past the current end of the implied array cause the array
to be extended. The file pointer can be read by the getFilePointer method and set by the seek in1.close();
out.close();
method.
in2=new RandomAccessFile("source2.txt","r");
It is generally true of all the reading routines in this class that if end-of-file is reached before out=new RandomAccessFile("target.txt","rw");
the desired number of bytes has been read, an EOFException (which is a kind of out.seek( out.length() );
IOException) is thrown. If any byte cannot be read for any reason other than end-of-file, an
con = new byte[(int)in2.length()];
IOException other than EOFException is thrown. In particular, an IOException may be thrown in2.readFully(con);
if the stream has been closed. out.write(con);
Since: out.writeUTF("end");
JDK1.0
in2.close();
out.close();
Constructor Summary }
}
RandomAccessFile(File file, String mode) Useful methods
Creates a random access file stream to read fro m, and optionally to write to, the file
specified by the File argu ment.
readByte() / writeByte() seek(long pos)- set the file pointer offset.
RandomAccessFile(String name, String mode) readInt() / writeInt() length()- Return the length of the file.
readDouble() / writeDouble() skip Bytes(int n)
Creates a random access file stream to read fro m, and optionally to write to, a file readBoolean() /writeBoolean()
with the specified name.
-9- (Java Notes 2003-4 Bar Ilan University)
EXCEPTION HANDLING:
public static void main (String[] args)
import java.io.*; {
import java.util.*; System.out.println("This is the Java IO Example");
IO test = new IO();
class IO DataInputStream file = null;
{ try
private String line; {
private StringTokenizer tokenizer; file = new DataInputStream(new
FileInputStream(“books.txt”));
public void newline(DataInputStream in) throws IOException }
{ catch (FileNotFoundException fnfe)
line = in.readLine(); {
if (line == null) System.out.println(“Could not find file. “
throw new EOFException(); + “Please place books.txt in main directory”);
tokenizer = new StringTokenizer(line); }
} try
{
public String readString(DataInputStream in) throws IOException while (true)
{ {
if (tokenizer == null) System.out.println(“Type: “ + test.readString(file));
newline(in); System.out.println(“Name: “ + test.readString(file));
while (true) System.out.println(“Cost1: “ + test.readDouble(file));
System.out.println(“Cost2: “ + test.readDouble(file));
{ }
try }
{ catch (EOFException exception)
return tokenizer.nextToken(); {
} //just exit the program
catch (NoSuchElementException exception) }
{ catch (IOException exception)
newline(in); {
} System.out.println(“Exception occurred: “
} + exception.getMessage());
} }
finally
public double readDouble(DataInputStream in) throws IOException
{ {
if (tokenizer == null) System.out.println(“This Line is printed anyhow.”);
newline(in); }
while (true) }
{ }
try
{
String str = tokenizer.nextToken();
return Double.valueOf(str.trim()).doubleValue();
}
catch (NoSuchElementException exception)
{
newline(in);
}
}
}
- 10 - (Java Notes 2003-4 Bar Ilan University)
class PrivateCar extends Car
INHERITANCE: {
final int LEATHER = 1;
class Car final int STANDARD = 0;
{ float engine;
boolean auto; int seats = LEATHER;
int price;
int maxSpeed = 120; PrivateCar()
{
Car() auto = false;
{ price = 150000;
auto = true; }
price = 100000;
} PrivateCar(float engine, int seats)
{
Car (boolean auto, int price) super(); //must be first command
{ this.engine = engine;
this.auto = auto; this.seats = seats;
this.price = price; super.speed(100);
} }
Car (int speed) public void speed(int max)
{ {
this(); //must be first command maxSpeed = max*2;
maxSpeed = speed; }
}
public static void main(String[] args)
public void speed (int max) {
{ PrivateCar a = new PrivateCar();
maxSpeed = max; a.speed(100);
} if (a instanceof PrivateCar)
System.out.println("a is a PrivateCar");
public int cost() }
{ }
return price;
}
public static void main(String[] args) protected- class is accessible jast for it’s subclasses and package members.
{ public - class is publicly accessible.
Car a = new Car(); abstract - class can’t be instantiated.
Car b = new Car(true, 120000); final - class can’t be subclassed.
b.speed(80);
int c = b.cost();
}
}
- 11 - (Java Notes 2003-4 Bar Ilan University)
INTERFACES:
class AmericanDisk extends IsraelDisk
interface ProductsInterface {
{ public double m_DollarRate;
public String getName();
public int getAvailableCount(); public AmericanDisk(String name,
public String getKind(); int avail, double cost, double rate)
public double getCost(); {
} super(name, avail, cost);
m_DollarRate = rate;
class Book implements ProductsInterface }
{
public String m_Name; public String getKind() {return super.getKind() +"[A]";}
public int m_Available; public double getCost() {return m_Cost * m_DollarRate;}
public double m_Cost; }
public Book(String name, int avail, double cost) class Inherit
{ {
m_Name = name; public static void main(String[] args)
m_Available = avail; {
m_Cost = cost; ProductsInterface[] arr = new ProductsInterface[3];
} arr[0] = new Book("My Michael - Amos Oz", 10, 56.50);
arr[1] = new IsraelDisk("Moon - Shlomo Artzi", 5,
public String getName() {return m_Name; } 87.90);
public int getAvailableCount() {return m_Available; } arr[2] = new AmericanDisk("Frozen - Madonna",
public String getKind() {return "Book";} 17, 21.23, 4.25);
public double getCost() {return m_Cost;}
} System.out.println("Kind \t\t Name \t\t\t Available “
+ ”\t\t Cost");
class IsraelDisk implements ProductsInterface for (int i=0; i<arr.length; i++)
{ {
public String m_Name; System.out.print(arr[i].getKind() + "\t\t");
public int m_Available; System.out.print(arr[i].getName() + "\t\t");
public double m_Cost; System.out.print(arr[i].getAvailableCount()+
"\t\t");
public IsraelDisk(String name, int avail, double cost) System.out.println(arr[i].getCost());
{ }
m_Name = name; }
m_Available = avail; }
m_Cost = cost;
}
OUTPUT:
public String getName() {return m_Name; } Kind Name Availab le Cost
public int getAvailableCount() {return m_Available; } Book My Michael - A mos Oz 10 56.5
public String getKind() {return "Disk";}
public double getCost() {return m_Cost;}
Disk Moon - Shlo mo Art zi 5 87.9
} Disk[A] Fro zen - Madonna 17 90.2275
- 12 - (Java Notes 2003-4 Bar Ilan University)
java.awt.* Awt Components:
Important event sources and their listeners: Label -For titles, legends, etc.
Event S ource Listener Button -Push buttons
TextCo mponent -Text input (TextField) & display (TextArea)
Window WindowListener Event Source
CheckBo x -On/Off or Yes/No checkbo xes
Button
List Co mboBo x -Popup choice list, only one choice
M enuItem ActionListener List/Choice -Displayed choice list, mu ltip le choices
TextField ScrollBar -Nu, Be’emet …
Event …
Choice
Usage: < container >.add( <co mponents>);
Checkbox ItemListener
List Example: Button b=new Button(“press”);
Panel.add(b);
The keyboabrd
(component) KeyListener Listener( method ) Layouts:
BorderLayout -North/South/East/West/Center (def. for Frames)
FlowLayout -Normal arrangement (def. for Panels, Applets)
Card Layout -Overlapping panels
Important listener interfaces and their methods: Grid Layout -Frame is divided into rows and colu mns
GridBag Layout -you can divid one row to nu m’ of colu mns,( vice versa).
null - lack of layout, the component set by coordinates.
Listener Interface Listener M ethods …
ActionListener actionPerformed(ActionEvent) Usage: < container >.setLayout( <Layout>);
focusGained(FocusEvent) or Examp le: Panel p = new Panel( new Grid Layout(2,2) );
FocusListener
focusLost(FocusEvent)
ItemListener itemStateChanged(ItemEvent) Check out: http://developer.java.sun.com/developer/technicalArticles/GUI/AWTLayoutMgr/index.h tml
keyPressed(KeyEvent) For an examp le on layouts.
KeyListener keyReleased(KeyEvent)
keyTyped(KeyEvent)
mouseClicked(M ouseEvent)
mouseEntered(M ouseEvent)
M ouseListener mouseExited(M ouseEvent)
mousePressed(M ouseEvent)
mouseReleased(M ouseEvent)
mouseDragged(M ouseEvent)
M ouseM otionListener
mouseM oved(M ouseEvent)
windowActivated(WindowEvent)
windowClosed(WindowEvent)
windowClosing(WindowEvent)
WindowListener windowDeactivated(WindowEvent)
windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpened(WindowEvent)
- 13 - (Java Notes 2003-4 Bar Ilan University)
Acti vatorAWT.java (AWT version) Acti vator.java (S wing version)
import java.awt.*; import java.awt.*;
import java.awt.event.*; import java.awt.event.*;
import javax.swing.*;
public class ActivatorAWT
{ public class Activator
public static void main(String[] args) {
{ public static void main(String[] args)
Button b; {
ActionListener al = new MyActionListener(); try
Frame f = new Frame("Hello Java"); {
UIManager.setLookAndFeel
f.add(b = new Button("Hola"), BorderLayout.NORTH);
b.setActionCommand("Hello"); ("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
b.addActionListener(al); }
catch (Exception e)
f.add(b=new Button("Aloha"), BorderLayout.CENTER); {
b.addActionListener(al); System.out.println("Exception: " + e.getMessage());
}
f.add(b = new Button("Adios"), BorderLayout.SOUTH);
b.setActionCommand("Quit"); JButton b;
b.addActionListener(al); ActionListener al = new MyActionListener();
JFrame f = new JFrame("Hello Java");
f.pack(); //always add contents to content pane. Never to
f.show(); Frame!!!
} Container c = f.getContentPane();
}
c.add(b = new JButton("Hola"), BorderLayout.NORTH);
class MyActionListener implements ActionListener b.setActionCommand("Hello");
{ b.addActionListener(al);
public void actionPerformed(ActionEvent e)
{ c.add(b=new JButton("Aloha"), BorderLayout.CENTER);
//Action Command is not necessarily la bel b.addActionListener(al);
String s = e.getActionCommand();
if (s.equals("Quit")) c.add(b = new JButton("Adios"), BorderLayout.SOUTH);
System.exit(0); b.setActionCommand("Quit");
b.addActionListener(al);
else if (s.equals("Hello"))
System.out.println("Bon Jour"); f.pack();
f.show();
else }
System.out.println(s + " selected"); }
} class MyActionListener looks exactly the same as before…
}
Other methods on frames:
other method:
setTitle(String title)
getSource()–return a reference (pointer) setBackground(Color col)
to the component that was activated. resize(int x, int y)
setLayout(LayoutManager manager)
hide()
- 14 - (Java Notes 2003-4 Bar Ilan University)
setVisible(boolean bool)
ItemListener
import java.awt.*; FocusListener
import java.awt.event.*;
import java.awt.*;
public class ItemEvApp extends Frame implements ItemListener import java.awt.event.*;
{
Checkbox[] c; public class FocusEvApp extends Frame imp lements FocusListener
Label label; {
GridLayout gl; Text Field[] tf;
ItemEvApp() public FocusEvApp()
{
gl= new GridLayout(3,2); {
setLayout(gl); setLayout( new Grid Layout(2,1) );
c =new Checkbox[4]; tf = new Text Field[2];
String[] labels = { "first","second","third","fourth" }; for(int i=0; i<2; i++)
{
for( int i=0; i<4; i++) tf[i]=new Text Field();
{ tf[i].addFocusListener(this);
c[i]=new Checkbox(labels[i]); add(tf[i]);
add(c[i]);
c[i].addItemListener(this);
}
} }
label=new Label(" chose a checkbox. "); public void focusGained(FocusEvent e)
add(label); {
} Object source = e.getSource();
public void itemStateChanged(ItemEvent e) if( source == tf[0] )
{ tf[0].setText(" I am in focus ");
if(e.getSource() == c[3])
else if( source == tf[1] )
label.setText("I am the fourth check box");
else tf[1].setText(" I am in focus ");
label.setText(e.getItem()+" was changed to "+e.getStateChange()); }
} public void focusLost(FocusEvent e)
public static void main(String[] args) {
{ Object source = e.getSource();
ItemEvApp app = new ItemEvApp(); if( source == tf[0] )
app.pack(); tf[0].setText(" I lost focus ");
app.show(); else if( source == tf[1] )
}
} tf[1].setText(" I lost focus ");
}
public static void main(St ring[] args)
{
FocusEvApp app = new FocusEvApp();
app.pack();
app.show();
}
}
- 15 - (Java Notes 2003-4 Bar Ilan University)
More on Listeners:
Anonymous inner classes:
Implementing an interface: public class MyClass extends JApplet
public class MyClass implements ActionListener {
{ ...
... someObject.addMouseListener(new MouseAdapter()
someObject.addActionListener(this); {
... public void mouseClicked(MouseEvent e)
{
public void actionPerformed(ActionEvent e) ... //Event Handler implementation goes here...
{ }
... //Event Handler implementation goes here... });
} ...
} }
Using Event Adapters:
To use an adapter, you create a subclass of it, instead of directly implementing Looks and feels supported by S wing:
a listener interface. javax.swing.plaf.metal.MetalLookAndFeel
com.sun.java.MotifLookAndFeel
/* com.sun.java.WindowsLookAndFeel
* An example of extending an adapter class instead of
* directly implementing a listener interface.
*/
public class MyClass extends MouseAdapter
{
...
someObject.addMouseListener(this);
...
public void mouseClicked(MouseEvent e)
{
... //Event Handler implementation goes here...
}
}
Inner classes:
//An example of using an inner class
public class MyClass extends JApplet
{
...
someObject.addMouseListener(new MyAdapter());
...
class MyAdapter extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
... //Event Handler implementation goes here...
}
}
}
- 16 - (Java Notes 2003-4 Bar Ilan University)
APPLETS
Example of an HTML file and Applet
Converting an applicati on to an applet:
Hello.java
1. Change all I/ O relevant to the user to awt interface
(System.out.println(…) g.drawstring(…)) import java.awt.*;
2. Ensure applet can be stopped by closing the window. import java.applet.*;
3. Import applet package: “import java.applet.*;”
public class Hello extends Applet
4. Extend Applet class instead of Frame class: {
class MyApplet extends Applet {… Font f;
5. main() method is no longer needed (can remain, but should call in it()) public void init()
6. Remove “setTitle(-) “ calls. {
7. Replace the constructor with init () String myFont= getParameter("font");
8. New default layout manager is “FlowLayout()”. Change it if needed. int mySize= Integer.parseInt(getParameter("size"));
9. Replace Frame calls with Applet ones f=new Font(myFont, Font.BOLD,mySize);
}
(dispose becomes destroy, createImage beco mes getImage, etc.)
public void paint(Graphics g)
10. Replace file I/O with URL I/O or getParameter fro m HTM L base {
document. g.setFont(f);
11. Create an HTM L file that refers to this applet g.setColor(Color.red);
12. Run HTM L file through appletviewer or Internet browser. g.drawString("Hello",5,40);
}
Applet Methods: }
Hello.html
public void in it() initialization functionality to the applet prior to
the first time the applet is started. <HTML>
public void start() called after the applet has been initialized (init <HEAD><TITLE> Hello world </TITLE></HEAD>
method), and every time the applet is reloaded in <BODY>
the browser. <H1> my first applet </H1>
public void stop() called by the browser when the containing web <APPLET CODE="Hello.class" CODEBASE="c:\myclasses"
page is replaced. WIDTH=600 HEIGHT=100>
public void destroy() destroys the applet and releases all its resources. <PARAM NAME=font VALUE="TimesRoman">
<PARAM NAME=size VALUE="40">
No Java support for APPLET !
public void paint( Graphics g ) </APPLET>
<BODY>
Important notes: </HTML>
1. Make main applet class public!
2. Create WWW directory under home d irectory and move all short: without parameters etc
relevant files into it. <APPLET CODE="Hello.class" WIDTH=600 HEIGHT=100>
</APPLET>
> mkdir WWW
3. Make WWW directory viewab le to others. archive: reduce time of download.
> ch mod 755 WWW <APPLET code="Hello.class" archive="Hello.jar" width=600
4. Make all files under WWW directory viewable to others. height=100 ></APPLET>
> ch mod 755 *.class *.gif
5. Make home directory v iewable to others and passable. new:
> ch mod 755 <login> <OBJECT CLASSID="java:Hello.class" HEIGHT=600 WIDTH=100>
</OBJECT>
- 17 - (Java Notes 2003-4 Bar Ilan University)
SoundAndImageApplet SoundAndImageAppletCanvas
import java.applet.*; import java.applet.*;
import java.awt.*; import java.awt.*;
import java.net.*; import java.net.*;
public class SoundAndImageApplet extends Applet public class SoundAndImageAppletCanvas extends Applet
{
{ AudioClip clip;
AudioClip clip; Image image;
Image image;
public void init()
public void init() {
{ setLayout( new GridLayout(1,1) );
setLayout( new GridLayout(1,1) );
URL imageURL=null; URL soundURL=null;
URL soundURL=null; URL imageURL=null;
try try
{ {
imageURL = new URL( getCodeBase(),"img.jpg" ); soundURL = new URL( getCodeBase(),"sound.au" );
soundURL = new URL( getCodeBase(),"sound.au" ); imageURL = new URL(getCodeBase(),"img.jpg");
} }
catch(MalformedURLException e){}
catch( MalformedURLException e ){}
clip = getAudioClip( soundURL);
image = getImage(imageURL); clip.loop();
image = getImage(imageURL);
clip = getAudioClip( soundURL);
add( new ImageDrawer(image) );
clip.loop(); }
} }
public void paint(Graphics g) class ImageDrawer extends Canvas
{ {
g.drawImage(image,0,0,getSize().width,getSize().height,this); Image image;
} public ImageDrawer(Image image)
} {
this.image = image;
}
public void paint(Graphics g)
{
g.drawImage(image,0,0,getSize().width,getSize().height,this);
}
}
- 18 - (Java Notes 2003-4 Bar Ilan University)
THREADS Example1:
There are two ways to create a new thread of execution. One is to declare a class to be a class SimpleThread extends Thread
subclass of Thread. This subclass should override the run method of class Thread. An {
public SimpleThread(String str)
instance of the subclass can then be allocated and started. For example, a thread that
{
computes primes larger than a stated value could be written as follows: super(str);
}
class PrimeThread extends Thread public void run()
{ {
long minPrime; for (int i=0; i<10; i++)
PrimeThread(long minPrime) {
{ System.out.println(i + " " + getName());
this.minPrime = minPrime; try
} {
sleep((long)(Math.random()*1000));
public void run() }
{ catch (InterruptedException e) {}
// compute primes larger than minPrime }
. . . System.out.println("Done! " + getName());
} }
} }
The following code would then create a thread and start it running:
PrimeThread p = new PrimeThread(143); public class TwoThreadsTest
p.start(); {
public static void main(String[] args)
{
The other way to create a thread is to declare a class that implements the Runnable interface. new SimpleThread("Jamaica").start();
That class then imp lements the run method. An instance of the class can then be allocated, new SimpleThread("Fiji").start();
passed as an argument when creating Thread, and started. The same examp le in this other }
style looks like the fo llo wing: }
class PrimeRun implements Runnable OUTPUT:
{ 0 Jamaica
long minPrime; 0 Fiji
PrimeRun(long minPrime) 1 Jamaica
{ 1 Fiji
this.minPrime = minPrime; 2 Fiji
} 2 Jamaica
3 Jamaica
public void run() 4 Jamaica
{ 3 Fiji
// compute primes larger than minPrime 4 Fiji
. . . …
} 8 Fiji
} 8 Jamaica
The following code would then create a thread and start it running: 9 Fiji
Done! Fiji
PrimeRun p = new PrimeRun(143); 9 Jamaica
new Thread(p).start(); Done! Jamaica
- 19 - (Java Notes 2003-4 Bar Ilan University)
Example2: Example3:
import java.awt.*; import java.awt.*;
import java.util.*; import java.util.*;
public class Clock extends Frame implements Runnable public class ThreadApp extends Frame
{ {
int sec; int sec=0;
Label time; Label time;
Thread runner; ClockThread runner;
public Clock(int sec) public ThreadApp()
{ {
this.sec=sec; time = new Label(sec+":");
time = new Label(sec+":"); add(time);
add(time); runner = new ClockThread( time );
start(); runner.start();
pack(); pack();
show(); show();
} }
public void start() public static void main( String[] args )
{ {
if( runner == null ) ThreadApp app=new ThreadApp();
{ }
runner=new Thread(this); }
runner.start();
} class ClockThread extends Thread
} {
public void stop() { runner = null; } Label time;
public void run() int sec;
{
while( runner != null ) public ClockThread(Label t)
{ {
sec++; time = t;
repaint(); }
try
{ public void run()
Thread.sleep(1000); {
} while( true )
catch(InterruptedException e){} {
} sec++;
} time.setText(sec+":");
public void paint( Graphics g ) try
{ {
time.setText(sec+":"); Thread.sleep(1000);
} }
public static void main( String[] args ) catch(InterruptedException e){}
{ }
Clock c=new Clock(0); }
} }
}
- 20 - (Java Notes 2003-4 Bar Ilan University)
NETWORKING IN JAVA
SERVER CLIENT
import java.io.*; import java.net.*;
import java.io.*;
import java.net.*;
import java.util.*; public class PrimeClient
{
public class PrimeServer public static final int PORT = 1301;// port out of the range of 1-1024
String hostName;
{ Socket soc;
private ServerSocket sSoc; public static void main(String args[]) throws IOException
public static final int PORT = 1301; // port out of the range of 1-1024 {
//replace localhost =>args[0] or with url
PrimeClient client = new PrimeClient("localhost");
public static void main(St ring args[]) throws IOException client.go();
{ }
PrimeServer server = new PrimeServer();
public PrimeClient(String hostString)
server.go(); {
} this.hostName = hostString;
public void go() throws IOException }
{
String readInput() throws IOException
Socket soc = null; {
sSoc = new ServerSocket(PORT); BufferedReader in =new BufferedReader(
while(t rue) new InputStreamReader(System.in));
return( in.readLine() );
{
}
soc = sSoc.accept(); // b locks until a connectio occurs
public void go() throws IOException
PrintWriter p w = new PrintWriter( //creating an OutputStream object {
soc = new Socket(hostName, PORT);
new OutputStreamWriter( BufferedReader ibr = new BufferedReader(
soc.getOutputStream()),true); new InputStreamReader(
Buffered Reader br = new BufferedReader( soc.getInputStream()));
new InputStreamReader(
PrintWriter pw = new PrintWriter(
soc.getInputStream())); new OutputStreamWriter(
int num = Integer.parseInt( br.read Line() ); soc.getOutputStream()),true);
pw.print ln( prime(num) );
p w.close(); System.out.println("************** Check Prime *************");
System.out.println("Enter a number.");
br.close(); pw.println( readInput() );
soc.close(); System.out.println(ibr.readLine());
}
ibr.close();
} pw.close();
String prime( int nu m ) soc.close();
{ }
for(int i=2; i*i<= nu m; i++) }
if( nu m%i==0 )
return(num +" is not a primary nu mber.");
return(nu m +" is a primary number.");
}
}
- 21 - (Java Notes 2003-4 Bar Ilan University)