Download JAVA NOTES FOR “PROGRAMMING LANGUAGES” AND

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

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

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