Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming E-mail: daher@rss.gov.jo Daher Thabit Daher Chief Architect E-mail: daher@rss.gov.jo.

Similar presentations


Presentation on theme: "Java Programming E-mail: daher@rss.gov.jo Daher Thabit Daher Chief Architect E-mail: daher@rss.gov.jo."— Presentation transcript:

1 Java Programming E-mail: daher@rss.gov.jo
Daher Thabit Daher Chief Architect

2 Contents Getting Started
Variables, Data Types, Operators, & Expressions Objects Data Structure Inheritance & Polymorphism Exceptions Java Database Connectivity (JDBC) Threading Java Applets I/O Streams

3 What is Java ? Primarily, Java is a programming language, an object-oriented language developed at Sun Microsystems. What is Java ? Between 1990 and 1993, James Gosling and others at Sun were working on a project that needed a new programming language. As a result, they developed Java. They originally created it for small, personal digital assistance in set top boxes. Their project was called *7 (Star Seven), and was part of a larger project called The Green Project.Java's original name was Oak, named after the tree outside James Gosling's office. But Oak turned out to be an existing programming language, so Sun named it Java, after many visits to a local coffee shop! Java is not an acronym. It is a trademark of Sun Microsystems.By 1993, James Gosling and others saw that the World Wide Web was beginning. And people like Arthur van Hoff and others at Sun developed a web browser that was originally named WebRunner and later HotJava.From 1993 to 1995, they showed HotJava to various companies, including Netscape Communications. The people at Netscape realized the power of Java and committed to incorporate it in their product. In 1995 and early 1996, companies began to license the Java technology and to incorporate it into their products.Beyond just the program language with its syntax and semantics, Java has something called a virtual machine. The Java virtual machine executes instructions that a Java compiler generates. This run time environment, or Java virtual machine, can be incorporated or embedded in various products, such as web browsers like Netscape Navigator. In addition, the Java virtual machine can also be incorporated into the kernel of the operating system, such as IBM's OS/2 operating system."

4 Some History In 1991, Sun Microsystems set up a research project to develop a language for programming ‘intelligent’ consumer electronics e.g. video recorders, TVs The language was called Oak (later changed to Java). Developed by James Gosling, and others.

5 August 1993: the project was cancelled.
The Web became popular during 1993. July 1994: Sun restarted work on Java as a Web programming language Java contains networking features, platform portability, and a small runtime system Java released May 1995 Netscape supported Java in Navigator 2.0, May 1996: JDK v.1.0 released. continued

6 February 1997: JDK v.1.1 released
major changes in the event model used by the GUI; inner classes introduced December 1998: JDK v.1.2 released also known as Java 2 much improved GUIs (SWING), graphics September 2000: JSDK v.1.3 released improved networking, sound, security see docs/relnotes/features.html

7 Java, JDK, JSDK, JRE There are several 'Java' names:
Java is the name of the language JDK is the old name for JSDK JSDK = "Java Software Development Kit" JSDK 1.3 JSDK 1.4 is available now (October 2001) continued

8 JRE = "Java Runtime System"
JSDK contains all the libraries (packages), compiler, and other tools for writing/running/debugging Java code. JRE = "Java Runtime System" a cut-down version of JSDK with only the packages/tools needed for running Java code most often used by Web browsers

9 JSDK Installation The current JSDK (v.1.3), its documentation, and excellent tutorials are here at: ftp://ftp.coe.psu.ac.th/pub/java/ The filenames are: j2sdk1_3_0-win.exe j2sdk-1_3_0-update1-doc.zip sun-java-tutorial.zip JSDK 1.3 for Windows continued

10 Update Autoexec.bat Add the bin path for Java to the PATH environment variable: set PATH=%PATH%;c:\jdk1.3.0_02\bin This says where the Java tools (e.g. javac) are located.

11 Why Java ? Simple Object-oriented Byte-code Interpreted Secure
Multithreaded Garbage Collected Portable High-performance Why Java ? Simple Java eliminates the pitfalls of the other languages ,such as pointer arithmetic and memory management that affect code robustness . Java was designed to make it much easier to write bug free code.The most important part of helping programmers write bug-free code is keeping the language simple.About half of the bugs in C and C++ programs are related to memory allocation and deallocation.Therefore the second important addition Java makes to providing bug-free code is automatic memory allocation and deallocation. Java is an excellent teaching language, and an excellent choice with which to learn programming. The language is small so it's easy to become fluent.The language is interpreted so the compile-run-link cycle is much shorter. The runtime environment provides automatic memory allocation and garbage collection so there's less for the programmer to think about. Java is object-oriented unlike Basic so the beginning programmer doesn't have to unlearn bad programming habits when moving into real world projects. Finally, it's very difficult (if not quite impossible) to write a Java program that will crash your system, something that you can't say about any other language. Object-oriented Is object-oriented to help the programmer visualize the program in real-life terms. Garbage Collection allocated memory that is no longer needed should be reallocated automatically. Portable Allows user code to be written once and run on multiple operating systems. Secure A means of checking code modules that are loaded to ensure security . Multithreaded A way for programs to run more than one thread of activity .

12 Java Advantages Productivity Simpler/safer than C, C++
object orientation (reuse) standard, large libraries (packages) Java Beans (component model) Simpler/safer than C, C++ no pointer arithmetic, automatic garbage collection, array bounds checking, etc. continued

13 Multithreading / concurrency
GUI features the event model the SWING and Abstract Windowing Toolkit (AWT) packages Multimedia graphics, animations, audio, video, etc. Network support communication with other machines/apps variety and standards: sockets, RMI, CORBA Multithreading / concurrency can run several ‘threads’ at once continued

14 Portablility / Platform Independence
“write once; run anywhere” continued

15 Java Development Kit (JDK) is free Good programming environments
Supports native code can integrate legacy code Java Development Kit (JDK) is free Good programming environments Visual Age ,Symantec Visual Cafe, Borland’s Jbuilder,Forte for Java,WSAD do not use them when first learning Java Good for teaching computing many important ideas in one place It’s new! continued

16 Java Disadvantages Java’s security restrictions makes some code hard to write: cannot “see” much of a local machine Slow Internet connections makes it difficult to download medium/large applets Lots to learn Java language (small) and Java libraries (very large)

17 Writing Java code There are two kinds of Java program:
Java applications ordinary programs; standalone Java applets run in a browser (or appletviewer) attached to Web pages, so can be downloaded easily from anywhere applets have access to browser features

18 Java Bytecodes The Java compiler (javac) generates bytecodes
a set of instructions similar to machine code not specific to any machine architecture A class file (holding bytecodes) can be run on any machine which has a Java runtime environment.

19 The Bytecode Advantage
Java runtime (Pentium) javac (Pentium) Java runtime (Mac) javac (Mac) Java code (.java file) Java bytecode (.class file) Java runtime (UNIX) javac (UNIX)

20 The Java Platform The Java Virtual Machine (Java VM)
The Java Application Programming Interface (Java API) Java Virtual Machine Reads compiled byte codes that are platform independent Is implemented as software or hardware Is implemented in a Java technology development tool or a Web browser .

21 Java Program Structure
Basic syntax of a Java class: <modifier> class <name> { <attribute_declaration> <constractor_declaration> <method_declaration> } Java Program Structure A program is made up of one or more classes A class contains one or more methods A method contains program statements A Java application always executes the main method

22 HelloWorld.java class HelloWorld {
public static void main (String args []) { System.out.println (“Hello World “); }

23 Declaring Attributes <modifier> <type> <name> [=<default_value>]; type:byte-short-int-long-char-float-double,boolean . Examples: Public class DeclarAttribute { public int x; private float y =1000.0; private String name =“Daher Thabit”; } Declaring Attributes The <name> can be any legal identifier. It is the name of the attribute being declared.There are several possible <modifier>,this declares that the attribute is accessible only to the methods within this class .

24 Declaring Methods <modifier> <return_type> <name>(<parameter>){ statements; } Parameter : (parameter_type parameter_name) Examples: public class Thing { private int x; public int getX(){ return x; public void setX(int new_x){ x = new_x; }} Declaring Methods To define methods, the Java programming language uses an approach that is similar to other languages,particularly C and C++. setter methods setter methods just set the value of a field (often private) in a class. getter methods getter methods just return the value of a field in a class.

25 Access Control Modifier Same class Same Package Subclass Universe public Yes protected default private Access Control Variables and methods can be at one of four access levels;public, protected,default,or private.Classes can be at the public or default. Variables and methods can be at one of four access levels: public, protected,default,or private. Classes can be at the public or default.

26 Comments Comments in a program are also called inline documentation
They should be included to explain the purpose of the program and describe processing steps Java comments can take two forms: // comment runs to the end of the line /* comment runs to terminating symbol, even across line breaks */

27 The Java API The Java Application Programmer Interface (API) is a collection of classes that can be used as needed The println and print methods are part of the Java API; they are not part of the Java language itself Both methods print information to the screen; the difference is that println moves to the next line when done,but print does not . The Java API

28 Class Libraries The Java API is a class library, a group of classes that support program development Classes in a class hierarchy are often related by inheritance The classes in the Java API is separated into packages The System class, for example, is in package java.lang Each package contains a set of classes that relate in some way

29 Import Statment Basic syntax of the package statement:
Import <pkg_name>.<sub_pkg_name>.<class_name>; Examples: import java.util.list; import java.io.*; import java.sql.*; Import Statement When you want to use packages ,use the import statement to tell the compiler Where to find the classes.

30 The Java API Packages Some packages in the Java API: java.applet
java.awt java.beans java.io java.lang java.math java.net java.rmi java.security java.sql java.text java.util

31 String Concatenation and Addition
The + operator serves two purposes When applied to two strings, they are combined into one (string concatenation) When applied to a string and some other value (like a number), that value is converted to a string and they are concatenated When applied to two numeric types, they are added together arithmetically

32 Command Line Arguments
Names.java The main method accepts extra information on the command line when a program is executed > java Names Daher Each extra value is called command line argument In Java, command line arguments are always read as a list of character strings Command Line Arguments Example class Names { public static void main (String args[]) System.out.println (args[0]); }

33 Variables Variable (Way)
Primitive type (byte,short,int,long,char,float,double,boolean) Reference type (String,array,…..) Variable (Place) inside a method (local) outside a method –member variable (global) Variables Declaration contains variable’s type and name int count; /* declaration: type = integer, name =count */ int count = 0; /* declaration and initialization */

34 Data Types Primitive Data Types
Variable contains single value (number, character, or boolean) Value of variable of type int is an integer Value of variable of type char is a 16-bit Unicode character (see

35 Data Types: Examples public static void main (String args[]) {
int count; String title; boolean isAsleep; . . . } You can give variables initial values: int numShoes, mySize, myAge = 33; String myName = ”ali”; boolean amTired = true; int a = 4, b = 5, c = 6; Data Types You can string together variable names: int x, y, z; String firstName, lastName;

36 Variables Variable Declaration Variable Initialization
int myInteger; Variable Initialization myInteger = 10; int count = 0; Final Variables (constants) final int aFinalVariable = 0; Variable Names In Java, a variable name must: be a legal Java identifier comprised of a series of Unicode characters not be a keyword or a Boolean literal (true or false) not have the same name as another variable in the same scope

37 Operators Unary operators, ex. ++ Binary operators, ex. =
prefix or postfix notation operator operand or operand operator Binary operators, ex. = infix notation operand1 operator operand2 Tertiary operator ?: expression ? Operand1 : operand2 Operators Operator returns value . Value and its type depend on the operator and the type of its operands. Operator Categories: arithmetic Operators(ex. addition, division) relational and conditional Operators bitwise and logical Operators Assignment Operators

38 The Conditional Operator
Java has a conditional operator that evaluates a boolean condition that determines which of two expressions is evaluated The result of the chosen expression is the result of the entire conditional operator Its syntax is: condition ? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated It is similar to an if-else statement, except that it is an expression that returns a value The Conditional Operator For example: larger = (num1 > num2) ? num1 : num2; If num1 is greater that num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger The conditional operator is ternary, meaning it requires three operands Another example: System.out.println ("Your change is " + count + (count == 1) ? “A" : “B"); If count equals 1, “A" is printed, otherwise “B" is printed.

39 Arithmetic Operators

40 The Increment and Decrement Operators
The increment and decrement operators can be applied in prefix (before the variable) or postfix (after the variable) form When used alone in a statement, the prefix and postfix forms are basically equivalent. That is, count++; is equivalent to ++count;

41 Example If count currently contains 45, then total = count++;
assigns 45 to total and 46 to count total = ++count; assigns the value 46 to both total and count

42 Relational Operators

43 Bitwise Operators

44 Assignment Operators Assigning one value to another Shortcuts
int count = 0; Shortcuts i = i + 2 i += 2; // These two are equivalent

45 Assignment Operators There are many such assignment operators, always written as op= , such as: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y

46 Expressions count++; Order of evaluation may matter
x * y * z // Order is unimportant x + y / 100 // Order is important here Expressions Used to: compute and assign values to variables help control the flow of execution Expressions: perform the computation return resulting value Expression is a series of variables, operators, and method calls Expression evaluates to single value .

47 Operator Precedence Operator Precedence
Can be modified by the use of parentheses Binary operators in the same expression are evaluated in left to right order

48 Branching Same as in C: if() switch() conditional expression ? :

49 The if/else Statements
if (expression) { statement(s) } if (response == OK) { // code to perform OK action } else { // code to perform Cancel action The if/else Statements if is A Java programming language keyword used to conduct a conditional test and execute a block of statements if the test evaluates to true.The if and the if-else statements are selection statements, allowing us to select which statement to perform next based on some boolean condition.

50 The switch Statement The syntax of the switch statement is:
switch (expression) { case value1: statement-list1 case value2: statement-list2 case … } The switch Statement Another selection construct, called the switch statement, provides another way to choose the next action.The switch statement evaluates an expression, then attempts to match the result to one of a series of values Execution transfers to statement list associated with the first value that matches.The expression must evaluate to an integral value, such as an integer or character The break statement is usually used to terminate the statement list of each case,which causes control to jump to the end of the switch statement and continue.A default case can be added to the end of the list of cases, and will execute if no other case matches.

51 Looping Same as in C: while() for() do/while() break continue

52 The while Statement while (expression) { statement }
In addition to while loops, Java has two other constructs used to perform repetition: the do statement the for statement The while Statement First, the while statement evaluates expression, which must return a boolean value. If the expression returns true, then the while statement executes the statement(s) associated with it. The while statement continues testing the expression and executing its block until the expression returns false. // This is the Hello program in Java class Hello { public static void main (String args[]) { int i; System.out.print("Hello "); // Say Hello i = 0; // Initialize loop counter while (i < 10) { // Test and Loop System.out.print(i); System.out.print(" "); i = i + 1; // Increment Loop Counter } System.out.println(); // Finish the line } }

53 The do Statement The do statement has the following syntax: do
while (condition); statement condition false true The do Statement The statement is executed until the condition becomes false It is similar to a while statement, except that its termination condition is evaluated after the loop body.The key difference between a do loop and a while loop is that the body of the do loop will execute at least once.If the condition of a while loop is false initially, the body of the loop is never executed Another way to put this is that a while loop will execute zero or more times and a do loop will execute one or more times.

54 The for Statement The syntax of the for loop is which is equivalent to
for (intialization; condition; increment) statement; which is equivalent to initialization; while (condition) { increment; } The for Statement Like a while loop, the condition of a for statement is tested prior to executing the loop body Therefore, a for loop will execute zero or more times It is well suited for executing a specific number of times, known in advance Note that the initialization portion is only performed once, but the increment portion is executed after each iteration.

55 Branching Statements The break statement The continue statement
The return statement Break out of a nested set of control structures (e.g. while, for, switch). Branching Statements The break statement has two forms: unlabeled and labeled. You saw the unlabeled form of the break statement used with switch earlier. As noted there, an unlabeled break terminates the enclosing switch statement, and flow of control transfers to the statement immediately following the switch. You can also use the unlabeled form of the break statement to terminate a for, while, or do-while loop.You use the continue statement to skip the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop, basically skipping the remainder of this iteration of the loop.The last of Java's branching statements is the return statement. You use return to exit from the current method. The flow of control returns to the statement that follows the original method call. The return statement has two forms: one that returns a value and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword: return ++count; The data type of the value returned by return must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value: return;

56 Control.java public static void main (String args[]){ int I;
class Control { public static void main (String args[]){ int I; for (I=0;I<10;I++){ System.out.println(I + “in for”); } while (true){ I--; if (I < 0) break; System.out.println(I + “in while”); }}

57 Constructing objects with new
To instantiate an object in Java, use the keyword new followed by a call to the class's constructor. create a new Car variable called c: Car c = new Car(); Constructing objects with new Here's how you'd create a new Car variable called c: Car c; c = new Car(); The first word, Car, declares the type of the variable c. Classes are types and variables of a class type need to be declared just like variables that are ints or doubles.The equals sign is the assignment operator and new is the construction operator.Finally notice the Car() method. The parentheses tell you this is a method and not a data type like the Car on the left hand side of the assignment.This is a constructor, a method that creates a new instance of a class.

58 class MyPoint { // declaring class MyPoint
int x; // declaring variables int y; // declaring methods void display() { System.out.println("x = " + x); System.out.println("y = " + y); } void setData(int a, int b) { x = a; y = b; int getX() { return x; int getY() { return y;

59 class Create { public static void main(String args[]) { MyPoint obj = new MyPoint(); // creating MyPoint class object // invoking methods obj.setData(10,20); obj.display(); obj.setData(30,40); System.out.println("Return val of getX : " + obj.getX()); System.out.println("Return val of getY : " + obj.getY()); }

60 Objects for Organizing Data
As our programs get more sophisticated, we need assistance organizing large amounts of data Chapter focuses on: array declaration and use arrays of objects parameters and arrays multidimensional arrays the Vector class additional techniques for managing strings Objects for Organizing Data A typical Java program creates many objects, which interact with one another by sending each other messages. Through these object interactions, a Java program can implement a GUI, run an animation, or send and receive information over a network.Once an object has completed the work for which it was created, it is garbage-collected and its resources are recycled for use by other objects.

61 Arrays An array is an ordered list of values
Each value has a numeric index An array of size N is indexed from zero to N-1 The following array of integers has a size of 10 and is indexed from 0 to 9 Arrays An array is a structure that holds multiple values of the same type. The length of an array is established when the array is created (atruntime). After creation, an array is a fixed-length structure. scores

62 Arrays A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression scores[4] refers to the value 67 (which is the 5th value in the array) That expression represents a place to store a single integer, can be used wherever an integer variable can For example, it can be assigned a value, printed, used in a calculation Arrays An array stores multiple values of the same type. That type can be primitive types or objects. Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc. In Java, the array itself is an object. Therefore the name of the array is a object reference variable, and the array itself is instantiated separately.

63 Declaring Arrays The scores array could be declared as follows:
int[] scores = new int[10]; An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas Examples: int[] units = {147, 323, 89, 933, 540,269, 97, 114, 298, 476}; char[] letter_grades = {'A', 'B', 'C','D','F'}; Declaring Arrays Some examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

64 Array Declarations Revisited
The brackets of the array type can be associated with the element type or with the name of the array. Therefore float[] prices; and float prices[]; are essentially equivalent The first format is usually more readable Array Declarations Revisited Like all other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. One array cannot store both ints and Strings, for instance. Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [] to indicate that this variable is an array.

65 Arrays of Objects The elements of an array can be object references
The declaration String[] words = new String[25]; reserves space to store 25 references to String objects It does NOT create the String objects them selves Each object stored in an array must be instantiated separately Arrays of Objects Objects can have arrays as instance variables Therefore, fairly complex structures can be created simply with arrays and objects. The software designer must carefully determine an organization of data and objects that makes sense for the situation.

66 Multidimensional Arrays
A one-dimensional array stores a simple list of values. A two-dimensional array can be thought of as a table of values, with rows and columns. A two-dimensional array element is referenced using two index values. To be precise, a two-dimensional array in Java is an array of arrays, therefore each row can have a different length. An initializer list can be used to create and set up a multidimensional array. Each element in the list is itself an initializer list. Note that each array dimension has its own length constant.

67 Declaring, Allocating and Initializing Two Dimensional Arrays
class FillArray { public static void main (String args[]) { int[][] matrix; matrix = new int[4][5]; for (int row=0; row < 4; row++) { for (int col=0; col < 5; col++) { matrix[row][col] = row+col; }} Declaring, Allocating and Initializing Two Dimensional Arrays Two dimensional arrays are declared, allocated and initialized much like one dimensional arrays. However you have to specify two dimensions rather than one, and you typically use two nested for loops to fill the array.

68 The Vector Class An object of class Vector is similar to an array in that it stores multiple values However, a vector only stores objects does not have the indexing syntax that arrays have Service methods are used to interact with a vector The Vector class is part of the java.util package

69 The Vector Class An important difference between an array and a vector is that a vector can be thought of as a dynamic, able to change its size as needed Each vector initially has a certain amount of memory space reserved for storing elements If an element is added that doesn't fit in the existing space, more room is automatically acquired. The Vector Class A vector is implemented using an array Whenever new space is required, a new, larger array is created, and the values are copied from the original to the new array.To insert an element, existing elements are first copied, one by one, to another position in the array Therefore, the implementation of Vector in the API is not very efficient.

70 import java.util.*; class MyVector { public static void main(String args[]) { Vector v = new Vector(); v.addElement("Hello"); // add as an element v.addElement(new Integer(100)); int length = v.size(); // the number of elements which the vector has for (int i = 0; i < length; i++) { System.out.println(v.elementAt(i)); // extracts the elements from the vector }

71 The String Class Creating a String Object
Four different ways (there are more). String color = “blue”; String s1; s1 = new String(“hello ”); char chs[] = {‘a’, ‘n’, ‘d’, ‘y’}; String s2 = new String(chs); s1 = s1 + s2 + “ davison”; // + is string concatenation

72 Comparing Strings lexicographical comparison
9 A Z a z 48 57 65 90 97 122 s1.equals(s2) lexicographical comparison returns true if s1 and s2 contain the same text s1 == s2 returns true if s1 and s2 refer to the same object continued

73 returns 0 if s1 and s2 are equal
s1.compareTo(s2) returns 0 if s1 and s2 are equal returns < 0 if s1 < s2; > 0 if s1 > s2 s1.startsWith(“text”) returns true if s1 starts with “text” s1.endsWith(“text”) returns true if s1 ends with “text”

74 Locating Things in Strings
for text analysis s1.indexOf(‘c’) returns index position of first ‘c’ in s1, otherwise -1 s1.lastIndexOf(‘c’) returns index position of last ‘c’ in s1, otherwise -1 Both of these can also take string arguments: s1.indexOf(“text”)

75 Extracting Substrings
s1.substring(5) returns the substring starting at index position 5 s1.substring(1, 4) returns substring between positions 1 and 3

76 Changing Strings return a new string; replace every ‘a’ by ‘d’
s1.replace(‘a’, ‘d’) return a new string; replace every ‘a’ by ‘d’ s1.toLowerCase() return a new string where every char has been converted to lowercase s1.trim() return a new string where any white space before or after the s1 text has been removed

77 Other String Methods The String class is in the java.lang package
there are many more String methods! e.g. s.length() Look at the Java documentation for the String class:

78

79 The StringTokeniser Class
This class provides a way of separating a string into tokens e.g. “hello Daher Thabit” becomes three tokens: “hello” “Daher” “Thabit” Very useful for parsing dividing a program into tokens representing variables, constants, keywords, numbers, etc.

80 The Basic Technique A String is converted to StringTokenizer, and then the tokens are removed one at a time inside a loop: String token: StringTokenizer st = new StringTokenizer( “...the string ...”); while ( st.hasMoreTokens() ) { token = st.nextToken(); : // do something with token } continued

81 StringTokenizer st = new StringTokenizer(...)
creates a sequence of tokens from the string the default separators are “\n\t\r” (newline, tab, carriage return) the separators can be changed st.hasMoreTokens() test if there are any more tokens left st.nextToken() returns the next token as a String object

82 Constructors Constructors create new instances of a class, that is objects. Constructors are special methods that have the same name as their class and no return type. Constructors class TwoDPoint { double x; double y; TwoDPoint(double xvalue, double yvalue) { this.x = xvalue; this.y = yvalue; }

83 class MyPoint { int x; int y; MyPoint() { // constructor with no argument System.out.println("called MyPoint()."); x = 0; y = 0; } MyPoint(int a, int b) { // constructor with two int value arguments System.out.println("called MyPoint(int, int)."); x = a; y = b;

84 void display() { System.out.println("x = " + x); System.out.println("y = " + y); } class Constructor { public static void main(String args[]) { MyPoint obj = new MyPoint(); // executing the constructor with no argument obj.display(); System.out.println(); MyPoint obj2 = new MyPoint(10, 20); // the constructor with two int value arguments executed obj2.display();

85 Overloading Overloading is when the same method or operator can be used on many different types of data. public void println(int i) public void println(float f) public void println() Overloading Methods can be overloaded as well. System.out.println() can print a double, a float, an int, a long, or a String.You don't do anything different depending on the type of number you want the value of. Overloading takes care of it.Programmer-defined classes can overload methods as well. To do this simply write two methods with the same name but different argument lists.

86 class MyPoint { int x; int y; // display() method with no parameter void display() { System.out.println("I don't have parameter."); System.out.println("x = " + x); System.out.println("y = " + y); } // display() method with two parameters void display(int a, int b) { x = a; y = b; System.out.println("I have two parameters.");

87 void setData(int a, int b) {
x = a; y = b; } class Overload { public static void main(String args[]) { MyPoint obj = new MyPoint(); obj.setData(10,20); obj.display(); // invoking display() method with no parameter obj.display(30,40); // invoking display() method with two int value parameters

88 Inheritance When a class inheritrs from only one class,it is called single inheritance. <modifier> class <name>[extends <superclass>] { <declarations> } Inheritance Code reusability is claimed to be a key advantage of object-oriented languages over non-object-oriented languages.Inheritance is the mechanism by which this is achieved. An object can inherit the variables and methods of another object.It can keep those it wants, and replace those it doesn't want.A subclass inherits all methods and variables from the superclass(parent class),it does not inherit constructors.

89 class MyPoint { // superclass MyPoint
private int x; private int y; public void setData(int a, int b) { x = a; y = b; } public void display() { System.out.println("x = " + x); System.out.println("y = " + y); class Derived extends MyPoint { // subclass Derived private int z; public void setData2(int c) { z = c;

90 public void display2() { System.out.println("z = " + z); }
class Inheri { public static void main(String args[]){ Derived obj = new Derived(); obj.setData(10,20); // invoking a method of a superclass obj.display(); obj.setData2(30); // invoking a method of a subclass obj.display2();

91 Overriding A subclass can modify behavior inherited from a parent class . A subclass can create a method with defferent functionality than the parents method but with the same: Name Return type Argument list Overriding If a method is defined in a subclass such that the name,return type,and argument list exactly math those of a method in the parent class,then the new method is said to override the old one.

92 class MyPoint { public void display() { System.out.println("display() in MyPoint."); } class Derived extends MyPoint { // overriding display() method of the superclass System.out.println("display() in Derived."); class Overridden { public static void main(String args[]) { Derived obj = new Derived(); // invoking the display() method of the Derived class obj.display();

93 Exception Handling Statements
general form of these statements: try { statement(s) } catch (exception type name) { } finally { } Exception Handling Statements The Java programming language provides a mechanism known as exceptions to help programs report and handle errors. When an error occurs, the program throws an exception. What does this mean? It means that the normal flow of the program is sinterrupted and that the runtime environment attempts to find an exception handler--a block of code that can handle a particular type of error. The exception handler can attempt to recover from the error or, if it determines that the error is unrecoverable, provide a gentle exit from the program. Three statements play a part in handling exceptions: The try statement identifies a block of statements within which an exception might be thrown. The catch statement must be associated with a try statement and identifies a block of statements that can handle a particular type of exception.The statements are executed if an exception of a particular type occurs within the try block. The finally statement must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block.

94 Exception Handling (in outline)
Format of code: statements; try { code...; } catch (Exception-type et) { code for dealing with et exception } more-statements; a try block a catch block

95 Basic Approach The programmer wraps the error-prone code inside a try block. If an exception (error) occurs anywhere in the code inside the try block, the catch block is executed immediately the block can use information stored in the et object After the catch block (the catch handler) has finished, execution continues after the catch block (in more-statements). execution does not return to the try block continued

96 Exception Handling (in more detail)
There can be many catch blocks associated with a try block . statements; try { code...; } catch (NullPointerException e) { code for dealing with a NULL pointer exception } catch (IOException e) { code for dealing with an IO exception } catch (MyOwnException e) { code for dealing with a user-defined exception } more-statements;

97 What can a catch handler do?
A handler can contain any Java code. Typical handler actions are to: print a message, and exit the program; or reset variables, and recall the method; or issue (throw) its own exception What if there is no exception? If the try block finishes successfully without causing an exception, then execution skips to the code after the catch block.

98 Types of Exceptions Common exceptions:
division by zero accessing an array outside its bounds Exceptions are organised into classes, with Exception being the most general.

99 User-defined Exceptions
The programmer can define new classes of exceptions by extending the Exception classes. Most commonly, the RuntimeException classes are extended to deal with new kinds of run-time errors.

100 The finally Block If a finally block is present it must be placed after the last catch handler. try { code...; } catch (Exception-type et) { code for dealing with et exception } finally { code...; } A finally block is always executed, even if: an exception is thrown inside the try block, or code does an ordinary return It is executed after the catch handler. Typical usage is to free system resources before terminating e.g. close files, network links

101 class ExTest { public static void main(String args[]) { int i = 0; String greetings [] = { "Hello world!", "No, I mean it!", "HELLO WORLD!!" }; while (i < 4) { // exception will be occured when refering to greetings[3] System.out.println(greetings[i]); i++; }

102 class ExTest2 { public static void main(String args[]) { int i = 0; String greetings [] = { "Hello world!", “Hi", “Welcome” }; while (i < 4) { try { System.out.println(greetings[i]); } catch (ArrayIndexOutOfBoundsException e) { // if an out-of-bounds access occures, // shows message and the program will be continued System.out.println("*** caught exception "); } finally { // executing finally block at any times System.out.println("This is always printed."); } i++;

103 Packages A Java package is a collection of classes
The package statement is used to specify that all classes defined in a file belong to a particular package. The syntax of the package statement is: package package-name; It must be located at the top of a file, and there can be only one package statement per file. Packages The classes in a package may or may not be related by inheritance. A package is used to group similar and interdependent classes together. The Java API is composed of multiple packages. A programmer can define a package and add classes to it. The import statement is used to assert that a particular program will use classes from a particular package. The import statement specifies particular classes, or an entire package of classes, that can be used in that program. Import statements are not necessary; a class can always be referenced by its fully qualified name in-line. If two classes from two packages have the same name and are used in the same program, they must be referenced by their fully qualified name. The classes must be organized in the directory structure such that they can be found when referenced by an import statement. There is a CLASSPATH environment variable on each computer system that determines where to look for classes when referenced. As a rule of thumb, if you will use only one class from a package, import that class specifically. If two or more classes will be used, use the * wildcard character in the import statement to provide access to all classes in the package.

104 Interfaces A Java interface is a collection of constants and abstract methods. A class that implements an interface must provide implementations for all of the methods defined in the interface This relationship is specified in the header of the class: class class-name implements interface-name { } Interfaces We've used the term interface to mean the set of service methods provided by an object. The Java language has an interface construct that formalizes this concept. An interface can be implemented by multiple classes. Each implementing class can provide their own unique version of the method definitions. An interface is not a class, and cannot be used to instantiate an object. An interface is not part of the class hierarchy. A class can be derived from a base class and implement one or more interfaces. Unlike interface methods, interface constants require nothing special of the implementing class.

105 Interfaces An interface can be derived from another interface, using the extends reserved word The child interface inherits the constants and abstract methods of the parent A class that implements the child interface must define all methods in both the parent and child Interfaces Note that the interface hierarchy and the class hierarchy are distinct. Note the similarities between interfaces and abstract classes both define abstract methods that are given definitions by a particular class. both can be used as generic type names for references. A class that implements multiple interfaces specifies all of them in its header, separated by commas. The ability to implement multiple interfaces provides many of the features of multiple inheritance, the ability to derive one class from two or more parents. Java does not support multiple inheritance. However, a class can implement multiple interfaces, but can only be derived from one class. An interface name can be used as a generic reference type name. A reference to any object of any class that implements that interface is compatible with that type.

106 What is JDBC? JDBC is an interface which allows Java code to execute SQL statements inside relational databases the databases must follow the ANSI SQL-2 standard What do we mean by JDBC Driver ? Java Database Connectivity (JDBC) technology is how the Java language works with databases, the Java Database Connectivity (JDBC) API, allows Java programs to access relational databases and interact with them.

107 JDBC in Use Java program JDBC driver for Oracle connectivity
data processing utilities driver for DB2 jdbc-odbc bridge odbc driver

108 Four Kinds of JDBC Driver
1. JDBC-ODBC Bridge translate Java to the ODBC API 2. Native API translate Java to the database’s own API 3. Native Protocol use Java to access the database more directly using its low level protocols 4. Net Protocol use Java to access the database via networking middleware (usually TCP/IP) required for networked applications

109 The JDBC-ODBC Bridge ODBC (Open Database Connectivity) is a Microsoft standard from the mid 1990’s. It is an API that allows programs to execute SQL inside databases ODBC is supported by many products. The JDBC-ODBC bridge comes free with the JDK: called sun.jdbc.odbc.JdbcOdbcDriver The ODBC driver for Microsoft Access comes with MS Office so it is easy to connect Java and Access Continued

110 JDBC Access Steps All JDBC programs do the following:
1) load (Register ) the JDBC driver Class.forName("oracle.jdbc.driver.OracleDriver"); 2) Specify the name and location of the database being used. String 3) Connect to the database with a Connection object Connection conn=DriverManager.getConnection(url); 4) Execute a SQL query using a Statement object String sql="select empno,ename from emp"; Statement stmt=conn.createStatement(); 5) Get the results in a ResultSet object Resultset rs=stmt.executeQuery(sql); 6) Finish by closing the ResultSet, Statement and Connection objects conn.close();

111 DriveManager Name the Database
It is responsible for establishing the connection to the database through the driver. e.g. Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriveManager.getConnection(url); Name the Database The name and location of the database is given as a URL the details of the URL vary depending on the type of database that is being used

112 ODBC Database URL jdbc:odbc: //host.domain.com: 2048 /data/file
The comms protocol The machine holding the database. The port used for the connection. The path to the database on the machine e.g. jdbc:odbc:Books

113 Statement Object The Statement object provides a ‘workspace’ where SQL queries can be created, executed, and results collected. e.g. Statement st = conn.createStatement(): ResultSet rs = st.executeQuery( “ select * from Authors” ); : st.close();

114 ResultSet Object Stores the results of a SQL query.
A ResultSet object is similar to a ‘table’ of answers, which can be examined by moving a ‘pointer’ (cursor). Continued

115 Cursor operations: Typical code:
23 Daher 5 Sirin 17 Emad 98 Odeh Cursor operations: first(), last(), next(), previous(), etc. Typical code: while( rs.next() ) { // process the row; }

116 simpJDBC.java // simpJDBC.java // Displays the firstnames and lastnames // of the Authors table in the Books db. import java.sql.*; public class simpJDBC { public static void main(String[] args) { // The URL for the Books database. // ’Protected' by a login and password. String url = "jdbc:odbc:Books"; String username = "anonymous"; String password = "guest"; :

117 try {. // load the JDBC-ODBC Bridge driver Class. forName("sun. jdbc
try { // load the JDBC-ODBC Bridge driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // connect to db using DriverManager Connection conn = DriverManager.getConnection( url, username, password ); // Create a statement object Statement statement = conn.createStatement(); // Execute the SQL query ResultSet rs = statement.executeQuery( "SELECT lastName, firstName FROM Authors" ); :

118 // Print the result set while( rs.next() ) System.out.println( rs.getString("lastName") + ", " rs.getString("firstName") ); // Close down statement.close(); conn.close(); } :

119 catch ( ClassNotFoundException cnfex ) { System. err
catch ( ClassNotFoundException cnfex ) { System.err.println( "Failed to load JDBC/ODBC driver." ); cnfex.printStackTrace(); System.exit( 1 ); // terminate program } catch ( SQLException sqlex ) { System.err.println( sqlex ); sqlex.printStackTrace(); } } // end of main() } // end of simpJDBC class

120 Username & Password The database’s link to the outside (e.g. its ODBC interface) must be configured to have a login and password

121 7. Books.mdb as an ODBC Data Source
1. Click on “32 bit ODBC” in the Control Panel. This displays the ODBC Data Sources Administrator

122 2. Press “Add’ to add a data source and select Microsoft Access Driver (*.mdb). Press “Finish”.

123 3. Type in a data source name,
description, and press “Select” to browse to set the path to the Books.mdb file. Now click on “Advanced”.

124 4. Type in a username and password (guest). Click “Ok”

125 Accessing a ResultSet The ResultSet class contains many methods for accessing the value of a column of the current row can use the column name or position e.g. get the value in the lastName column: rs.getString("lastName") The values are SQL data, and so must be converted to Java types/objects. There are many methods for accessing/converting the data, e.g. getString(), getDate(), getInt(), getFloat(), getObject()

126 SQL Statements They can be defined into two types:
those using the Data Definition Language (DDL) create, delete tables those using the Data Manipulation Language (DML) select others, including insert, update, delete

127 Executing DDL and DML select statements are executed from JDBC with executeQuery(). The method returns a table of results (a resultSet object). e.g. ResultSet rs = statement.executeQuery( "SELECT lastName, firstName FROM Authors" ); continued

128 executeUpdate() But most SQL statements do not return a table
DDL statements, e.g. create, drop most DML statements, e.g. insert, update If you try to execute these kinds of statements with executeQuery(), an SQLException will occur. executeUpdate Used to execute SQL statements that change the database, table, or row e.g. DDL: create, drop e.g. DML: insert, update, delete

129 BuildTables.java This program uses create and insert to build a new table, called urlInfo, inside Books.mdb.

130 Code // BuildTables.java // Create a new table, urlInfo, inside Books.mdb // The table has three columns: id, name, url import java.sql.*; public class simpJDBC { public static void main(String[] args) { // The URL for the Books database. // ’Protected' by a login and password. String url = "jdbc:odbc:Books"; String username = "anonymous"; String password = "guest"; :

131 // SQL table creation and insertion String[] SQLStats = {
// SQL table creation and insertion String[] SQLStats = { "create table urlInfo (id int,Name char(48), url char(80))", "insert into urlInfo values(1, ‘Daher Thabit', 'http://www.rss.gov.jo/~daher')", "insert into urlInfo values(2, ‘National Information Centre', 'http://www.nic.gov.jo')", "insert into urlInfo values(3, ‘Sun', 'http://www.sun.com')” }; try { // load the JDBC-ODBC Bridge driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // connect to db using DriverManager Connection conn = DriverManager.getConnection( url, username, password ); :

132 // Create a statement object. Statement statement =. conn
// Create a statement object Statement statement = conn.createStatement(); // Create urlInfo table for (int i = 0; i < SQLStats.length; i++) { statement.executeUpdate(SQLStats[i]); System.out.println("Processed: " SQLStats[i]); } // Close down statement.close(); conn.close(); } :

133 catch ( ClassNotFoundException cnfex ) { System. err
catch ( ClassNotFoundException cnfex ) { System.err.println( "Failed to load JDBC/ODBC driver." ); cnfex.printStackTrace(); System.exit( 1 ); // terminate program } catch ( SQLException sqlex ) { System.err.println( sqlex ); sqlex.printStackTrace(); } } // end of main() } // end of BuildTables class

134 Current Information: A searchable list of drivers (freeware, shareware, and commercial) can be found at: jdbc/drivers

135 Threading Threads Objectives describe basic threads in Java

136 Contents 1. What is Concurrency? 2. Java Threads 3. Scheduling

137 1. What is Concurrency? Concurrency (parallelism) allows several tasks/jobs to be done at the same time. For example: a person can walk, talk and breath at the same time a computer can compile a program, print a file, and receive at the same time Most programming languages do not have concurrent features e.g. a program that cannot do several tasks at once continued

138 Java’s concurrent language features (called threads).
C does not have concurrency features, but it can use concurrency functions from UNIX leads to code that is low level, and hard to understand The first mainstream language to have concurrent language features was Ada (~1980). Java’s concurrent language features (called threads).

139 2. Java Threads A program can have many threads of execution
each thread runs concurrently and does one task e.g. a program can have several threads download large audio files from the Web, and another thread play the files as they arrive

140 2.1. Two Ways to Make a Thread
1. Extend class Thread and override run(): class Mango extends Thread { public void run() { /* do task */ } } // Thread creation Mango m = new Mango(); m.start(); continued

141 2. Implement the Runnable interface and override run():
class Pineapple implements Runnable { public void run() { /* do task */ } } // Thread creation Thread pat1 = new Thread( new Pineapple() ); pat1.start();

142 2.2. start() and run() Threads do not automatically start executing when created (with new) they must be started with start() start() will automatically call run() Programmers override run(); they do not alter start()

143 2.3. threadExs.java continued
// The two ways to obtain a thread of code // extend class Thread // implement the Runnable interface import java.io.*; class threadExs { public static void main(String[] a) { SimpThread t1 = new SimpThread(); t1.start(); Thread t2 = new Thread (new SimpRunnable()); t2.start(); } } continued

144 class SimpThread extends Thread { // 1. extend class java. lang
class SimpThread extends Thread { // extend class java.lang.Thread public void run() { for(int i = 0; i < 300; i++) System.out.println(i ". Extension of THREAD running"); } } class SimpRunnable implements Runnable { // implement the Runnable interface, public void run() { for (int i = 0; i < 300; i++) System.out.println(i ". Implem. of RUNNABLE running"); } }

145 Usage t1 starts t1 and t2 alternate t1 ends and t2 continues
$ java threadExs 0. Extension of THREAD running 1. Extension of THREAD running 2. Extension of THREAD running : 17. Extension of THREAD running 0. Implem. of RUNNABLE running 18. Extension of THREAD running 1. Implem. of RUNNABLE running : 299. Extension of THREAD running 282. Implem. of RUNNABLE running 299. Implem. of RUNNABLE running : 282. Implem. of RUNNABLE running $ t1 starts t1 and t2 alternate t1 ends and t2 continues

146 2.4. Runnable vs. Thread The Thread class contains a range of useful methods: run(), sleep(), getName(), etc. The Runnable interface only has run() but once a Runnable object is running as a thread, a Thread object for it can be accessed then the Thread methods can be used

147 2.5. threadExs2.java A thread and a Runnable object that both sleep
import java.io.*; class threadExs2 { public static void main(String[] a) { SleepThread t1 = new SleepThread(); t1.start(); Thread t2 = new Thread (new SleepRunnable()); t2.start(); } }

148 class SleepThread extends Thread { public void run() { for(int i = 0; i < 300; i++) { System.out.println(i ". Extension of THREAD running"); if (i == 50) { System.out.println( "**** SleepThread going to sleep"); try{ sleep(5000); } catch (InterruptedException ie) { return; } System.out.println( "**** SleepThread waking up"); } } } }

149 class SleepRunnable implements Runnable { public void run() { for (int i = 0; i < 300; i++) { System.out.println(i ". Implem. of RUNNABLE running"); if (i == 250) { System.out.println( "**** SleepRunnable going to sleep"); Thread rt = Thread.currentThread(); try{ rt.sleep(7000); } catch (InterruptedException ie) {return; } System.out.println( "**** SleepRunnable waking up"); } } } }

150 Usage t1 starts t1 and t2 alternate t1 goes to sleep t2 runs alone
0. Extension of THREAD running 1. Extension of THREAD running 2. Extension of THREAD running : 17. Extension of THREAD running 0. Implem. of RUNNABLE running 18. Extension of THREAD running 1. Implem. of RUNNABLE running : 50. Extension of THREAD running 33. Implem. of RUNNABLE running **** SleepThread going to sleep 34. Implem. of RUNNABLE running 35. Implem. of RUNNABLE running : t1 starts t1 and t2 alternate t1 goes to sleep t2 runs alone

151 t2 goes to sleep later, t1 wakes up t1 runs alone to its finish
250. Implem. of RUNNABLE running **** SleepRunnable going to sleep **** SleepThread waking up 51. Extension of THREAD running 52. Extension of THREAD running : 299. Extension of THREAD running **** SleepRunnable waking up 251. Implem. of RUNNABLE running 252. Implem. of RUNNABLE running : 299. Implem. of RUNNABLE running $ t2 goes to sleep later, t1 wakes up t1 runs alone to its finish later, t2 wakes up t2 runs to to its finish

152 2.6. Why use Runnable? The big advantage of Runnable is that it is an interface: a class can implement many interfaces, but can only extend one class. e.g class FooBar extends JApplet implements Runnable, ActionListener but not: class FooBar extends JApplet, Thread implements ActionListener ERROR

153 3. Scheduling The JVM scheduler decides how much time to give to each thread for running. Most schedulers use time slicing. 1) Each thread gets a small amount of time to run (called a time slice). 2) When the time is used up, the thread is automatically suspended (if it has not finished). i.e. the execution of run() is suspended continued

154 3) The suspended thread waits until all the other threads have had a turn, before it is automatically woken up i.e. the execution of run() starts from where it was suspended The idea of giving each thread a turn is called round-robin scheduling. There are many other scheduling algorithms e.g. threads can have different priorities a high priority thread can get a turn more quickly

155 3.1. Scheduling Problem in Java
Java on different OSes do not use the same scheduling mechanism Java on Windows uses time slices and round-robin scheduling every threads gets a turn Java on Solaris does not use time slices a thread executes until it finishes; others must wait good bad continued

156 How can threads be made to give turns?
the yield() function can be called in a thread to force it to time slice yield() is also sometimes useful in Windows-based code to make the time slicing happen more often In the future, all the JVMs will use time slicing

157 3.2. drinks.java Using yield() to improve fairness in Window continued
public class drinks { public static void main(String[] a) { Coffee cof1 = new Coffee(300); cof1.start(); // an anonymous thread new Coffee(270).start(); new Tea(250).start(); // another anon. thread } } continued

158 class Coffee extends Thread { private int numCups; public Coffee(int n) { numCups = n; } public void run() { while(numCups > 0) { System.out.println(numCups + ". " getName() + " likes coffee"); numCups--; yield(); // must appear for solaris; // optional in Win9x } } } continued

159 class Tea extends Thread { private int numCups; public Tea(int n) { numCups = n; } public void run() { while(numCups > 0) { System.out.println(numCups ". I like tea"); numCups--; yield(); // must appear for solaris; // optional in Win9x } } }

160 Usage with the yield() calls commented out tea thread begins
$ java drinks 250. I like tea : 242. I like tea 300. Thread-0 likes coffee 299. Thread-0 likes coffee : 259. Thread-0 likes coffee 258. Thread-0 likes coffee 241. I like tea 270. Thread-1 likes coffee 257. Thread-0 likes coffee 240. I like tea 269. Thread-1 likes coffee 256. Thread-0 likes coffee : tea thread begins first coffee thread begins second coffee thread begins continued

161 tea thread finishes first coffee thread finishes second coffee
2. I like tea 31. Thread-1 likes coffee 18. Thread-0 likes coffee 1. I like tea : 30. Thread-1 likes coffee 17. Thread-0 likes coffee 29. Thread-1 likes coffee 16. Thread-0 likes coffee : 15. Thread-1 likes coffee 2. Thread-0 likes coffee 14. Thread-1 likes coffee 1. Thread-0 likes coffee 13. Thread-1 likes coffee 12. Thread-1 likes coffee : 2. Thread-1 likes coffee 1. Thread-1 likes coffee $ tea thread finishes first coffee thread finishes second coffee thread finishes

162 Usage with the yield() calls in The three threads start together
$ java drinks 300. Thread-0 likes coffee 270. Thread-1 likes coffee 250. I like tea 299. Thread-0 likes coffee 269. Thread-1 likes coffee 249. I like tea : 22. Thread-1 likes coffee 52. Thread-0 likes coffee 2. I like tea 21. Thread-1 likes coffee 51. Thread-0 likes coffee 1. I like tea : The three threads start together tea thread finishes continued

163 second coffee thread finishes first coffee thread finishes
20. Thread-1 likes coffee 50. Thread-0 likes coffee 19. Thread-1 likes coffee 49. Thread-0 likes coffee : 2. Thread-1 likes coffee 32. Thread-0 likes coffee 1. Thread-1 likes coffee 31. Thread-0 likes coffee 30. Thread-0 likes coffee : 2. Thread-0 likes coffee 1. Thread-0 likes coffee $ second coffee thread finishes first coffee thread finishes

164 Graphics Objective look at color, fonts, and how to draw shapes into applet/application windows

165 Graphics Objective look at color, fonts, and how to draw shapes into applet/application windows

166 Java’s Coordinate System
Graphical methods use an (X,Y) coordinate system to place things in a window: +x X axis (X,Y) note +y Y axis

167 Coordinate Coordinate
Java uses the standard, two-dimensional, computer graphics coordinate system.The first visible pixel in the upper left-hand corner of the applet canvas is (0, 0).Coordinates increase to the right and down.

168 Graphics Objects and Contexts
Drawing graphics into an applet/application window is a two-stage process: 1) the graphics object for the window must be obtained 2) drawing is done into the window by calling methods in the graphics object window graphics object call methods continued

169 A graphics object contains methods and data related to drawing:
e.g. the drawing area, current font, color often called a graphics context Graphics objects are instances of the Graphics class. continued

170 Good news: The programmer does not have to directly obtain the graphics object for the applet/application window the runtime system supplies it as an argument to paint() the programmer must redefine paint() to modify/use its graphics object argument

171 Graphics Methods: paint()
public void paint(Graphics g); draws the graphics context stored in g which represents the applet/application window called by the runtime system at certain times the programmer does not call paint() directly continued

172 paint() is called automatically at the start to draw the window, and whenever the window needs to be redisplayed e.g when the window was hidden and is uncovered

173 repaint() its default behaviour is to call update() and then paint()
public void repaint() its default behaviour is to call update() and then paint() programmers often call this method directly in order to request a repaint of the window a variation of repaint() specifies a subregion of the window to repaint repaint(x,y,width,height) the rest of the window is unchanged

174 show() Sometimes used in applications to make the window visible.

175 Drawing Methods The names of the methods for drawing text, lines, shapes, etc. are very similar: public void drawXXX(...); public void fillXXX(...); “XXX” is replaced by String, Line, Rect, RoundRect, 3DRect, Arc, Polygon, ... continued

176 The drawing colour is the ‘foreground’ colour
drawXXX() puts an empty outline on the screen. fillXXX() fills the interior with a solid colour. The drawing colour is the ‘foreground’ colour set with setColor(Color c)

177 What is an Applet ? An Applet is a Java class that you can embed in an HTML page, and is downloaded and executed by a Web browser. What is an Applet ? An applet runs in the environment of a Web browser,so it is not started directly by typing a command.You must create an HTML file that tells the browser what to load and how to run it.You then point the browser at the URL that specifies that HTML file.

178 Applet Class Hierarchy
java.lang.Object java.awt.Component java.awt.Container java.awt.Window java.awt.Panel java.awt.Frame java.applet.Applet Applet Class Hierarchy This hierarchy shows that you can use an applet directly as the starting point for an AWT layout.Because an applet is a Panel, it has a FlowLayout manager by default.

179 Java Applets Java source Java compiler code bytecode Web browser
interpreter Web browser Java Applets A Java applet is a Java program that is intended to be sent across a network and executed using a Web browser A Java application is a stand alone program Applications have a main method, but applets do not Applets are derived from the java.applet.Applet class Links to applets can be embedded in HTML documents

180 MyApplet.java import java.applet.*; import java.awt.*;
public class MyApplet extends Applet {  public void paint(Graphics g) { ……………….; ………………..; } MyApplet.java Compile the applet in the same directory as the html file, to produce a MyApplet.class binary file: c:\jdk1.2\bin\javac MyApplet.java Then run Netscape Communicator or Internet Explorer and open the HTML document to watch your applet run.

181 Simple HTML document <HTML> <HEAD>
<TITLE>My First Applet</TITLE> </HEAD> <BODY> <APPLET code=”MyApplet.class” width=500 height=300> </APPLET> </BODY> </HTML> Simple HTML document You can load applet class into a web browser using the APPLET tags in HTML,or you can run it using a special java application called an Applet Viewer: c:\jdk1.2\bin\ appletviewer MyFirstApplet.html

182 Drawing String Example
import java.applet.*; import java.awt.*;   public class MyApplet extends Applet {  public void paint(Graphics g) { g.drawString(“Hello Daher”,25,25); // x and y } Drawing String Example where (x, y) are the points and g is the Graphics object you're drawing with.

183 What is the appletviewer ?
A Java application that: Enables you to run applets without using a Web browser. Loads the HTML file supplied as an argument What is the appletviewer ? An applet is usually run inside a web browser, such as HotJava ,Internet Explorer or the Netscape Navigator,which is capable of running Java software programs.To simplify and speed up development,the Java 2 SDK comes with a tool designed only to view applets,not HTML pages.This tool is the appletviewer. Example appletviewer HelloWorld.html

184 Applet Life Cycle public void init(); public void start();
public void stop(); public void destroy(); Applet Life Cycle There are three major methods that relate to applet lifecycle : init() Called when the applet is created. Can be used to initialize data values. public void init() { // } start() Called when the applet becomes visible.This method is typically used to start threads or an animation or to play sounds. public void start() { musicClip.play(); stop() called when the applet becomes invisible.The applet uses this method to stop any functionality that should not occupy the CPU when the applet is not on the current browser page. public void stop() { musicClip.stop();

185 Colors A colour is defined using an RGB (Red/Green/Blue) triplet of values: 3 integers, each in the range 0 to 255 (or 3 floats, each in the range 0.0 to 1.0) as a number gets bigger, so the amount of color increases 0 = black (off) 1 = full on

186 Colors Color is not a property of a particular rectangle,string or other thing you may draw. Rather color is a part of the Graphics object that does the drawing. To change colors you change the color of your Graphics object. Then everything you draw from that point forward will be in the new color, at least until you change it again. Colors When an applet starts running the color is set to black by default.You can change this to red by calling g.setColor(Color.red).You can change it back to black by calling g.setColor(Color.black).The following code fragment shows how you'd draw a pink String followed by a green one: g.setColor(Color.pink); g.drawString("This String is pink!", 50, 25); g.setColor(Color.green); g.drawString("This String is green!", 50, 50); Color is a class in the AWT. Individual colors like red or mauve are instances of this class, java.awt.Color. Be sure to import it if you want to use other than the default colors.You create new colors using the same RGB triples that you use to set background colors on web pages.However you use decimal numbers instead of the hex values used by the bgcolor tag.For example medium gray is Color(127, 127, 127). Pure white is Color(255, 255, 255).Pure red is (255, 0, 0) and so on.As with any variable you should give your colors descriptive names. For instance Color medGray = new Color(127, 127, 127); Color cream = new Color(255, 231, 187); Color lightGreen = new Color(0, 55, 0);

187 Predefined Colors Color RGB triple public final static Color orange 255,200,0 public final static Color pink 255,175,175 public final static Color black 0,0,0 public final static Color white 255,255,255 public final static Color red 255,0,0 public final static Color green 0,255,0 public final static Color blue 0,0, :

188 Common Colors Color.black Color.blue Color.cyan Color.darkGray
Color.gray Color.green Color.lightGray Color.magenta Color.orange Color.pink Color.red Color.white Color.yellow Common Colors before you start messing with the color of the pen its a good idea to make sure you can go back to the color you started with.For this purpose Java provides the getColor() method. You use it like follows: Color oldColor = g.getColor(); g.setColor(Color.pink); g.drawString("This String is pink!", 50, 25); g.setColor(Color.green); g.drawString("This String is green!", 50, 50); g.setColor(oldColor);

189 Color Methods creates a Color object based on the RGB values
public Color(int r, int g, int b); public Color(float r, float g, float b); creates a Color object based on the RGB values e.g. Color c = new Color(0,0,0); public abstract void setColor(Color c); sets the foreground colour of the graphics object e.g. g.setColor(c); continued

190 returns the colour value as an int e.g. c.getRed();
public abstract Color getColor(); returns a Color object set to the foreground colour of the graphics object e.g. c = g.getColor(); public int getRed(); public int getBlue(); public int getGreen(); returns the colour value as an int e.g. c.getRed();

191 Fonts A Font object is defined using three attributes:
its name (e.g. “TimesRoman”) its style (e.g. ITALIC) its point size (e.g. 24) continued

192 Creating a Font object:
public Font(String name, int style, int size); e.g. Font f = new Font(“TimesRoman”, Font.BOLD, 18); Set the graphic object’s font: public abstract void setFont(Font f); e.g. g.setFont(f); continued

193 Five font names can be assumed:
Monospaced Serif SansSerif Five font names can be assumed: TimesRoman, Courier, Helvetica, Symbol, Dialog Some style constants in the Font class: public final static int PLAIN public final static int BOLD public final static int ITALIC

194 Lines, Rectangles, Ovals
public void drawline( int x1, int y1, int x2, int y2); draw a line between (x1,y1) and (x2,y2) in the current colour (x1,y1) (x2,y2)

195 Drawing Lines import java.applet.*; import java.awt.*;
public class SimpleLine extends Applet { public void paint(Graphics g) { g.drawLine(5,10,20,30); } Drawing Lines Drawing straight lines with Java is easy. Just call g.drawLine(x1, y1, x2, y2) where (x1, y1) and (x2, y2) are the endpoints of your lines and g is the Graphics object you're drawing with.

196 (x,y) width 2. Rectangles height public void drawRect(int x, int y, int width, int height); draw a rectangle of the specified width and height. Its top-left corner is at (x,y). public void fillRect(int x, int y, int width, int height); draw a solid rectangle. Use the current foreground colour. continued

197 Use the current background colour (i.e. the colour of the window).
rectangle window public void clearRect(int x, int y, int width, int height); Use the current background colour (i.e. the colour of the window). Frequently used to ‘erase’ something by covering it with the background colour

198 Drawing Rectangles import java.applet.*; import java.awt.*;
public class RectangleApplet extends Applet { public void paint(Graphics g) { g.drawRect(35,15, 125,200); } Drawing Rectangles Drawing rectangles is simple. Start with a Graphics object g and call its drawRect() method: public void drawRect(int x, int y, int width, int height) As the variable names suggest, the first int is the left hand side of the rectangle,the second is the top of the rectangle, the third is the width and the fourth is the height. This is in contrast to some APIs where the four sides of the rectangle are given.This uses drawRect() to draw a rectangle around the sides of an applet.

199 3. Rounded Rectangles A rectangle with rounded corners: arc height
(x, y) arc width height width continued

200 public void drawRoundRect(. int x, int y,. int width, int height,
public void drawRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight); public void fillRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight);

201 4. 3D Rectangles These are ordinary rectangles with shading along two edges, to make them look three dimensional. Two types: raised and lowered continued

202 The rectangle is raised if raised is true; otherwise lowered.
public void draw3DRect( int x, int y, int width, int height, Boolean raised); The rectangle is raised if raised is true; otherwise lowered. public void fill3DRect( int x, int y, int width, int height, Boolean raised);

203 5. Ovals and Circles Dimensions of an oval: (x, y) height width
public void drawOval(int left, int top, int width, int height) public void fillOval(int left, int top, int width, int height) The arguments to drawOval() are the same as the arguments to drawRect().The first int is the left hand side of the enclosing rectangle, the second is the top of the enclosing rectangle, the third is the width and the fourth is the height.There is no special method to draw a circle. Just draw an oval inside a square.Java also has methods to draw outlined and filled arcs. They're similar to drawOval() and fillOval() but you must also specify a starting and ending angle for the arc. Angles are given in degrees.The signatures are: public void drawArc(int left, int top, int width, int height, int startangle, int stopangle) public void fillArc(int left, int top, int width, int height, width continued

204 public void drawOval( int x, int y, int width, int height);
public void fillOval( int x, int y, int width, int height);

205 6. Arcs An arc is a portion of an oval.
An arc is drawn between two angles: a starting angle and and an arc (ending) angle 90 (x,y) 0 degrees height 180 starting angle ending angle width 270 continued

206 A negative sweep measures the angle in the “clockwise’ direction
positive sweep negative sweep A positive sweep measures the angle in the “counter-clockwise” direction the angle is a positive value (e.g. 275) A negative sweep measures the angle in the “clockwise’ direction the angle is a negative value (e.g. -85) continued

207 a positive number means “positive
sweep”; negative means “negative sweep” public void drawArc( int x, int y, int width, int height, int startAngle, int arcAngle); public void fillArc( int x, int y, int width, int height, int startAngle, int arcAngle);

208 Examples

209 7. Polygons and Polylines
Polygons are multi-sided shapes, represented by a series of (x,y) points. Polylines are a series of points connected by straight lines. continued

210 Polygons are closed shapes. Polylines may be open or closed
an open polyline does not end where it began e.g. the example on the previous slide Only polygons can be filled with colour since they are closed

211 Polygon Methods public Polygon(int xs[], int ys[], int num); returns a new Polygon object with num sides; x coordinates from xs[], y coordinates from ys[] e.g. int xs = {20,30,20}; int ys = {20,30,40}; Polygon p = new Polygon(xs,ys,3); continued

212 draw the polygon p in the graphics object e.g. g.drawPolygon(p);
(20,20) (30,30) (20,40) public void drawPolygon(Polygon p); draw the polygon p in the graphics object e.g. g.drawPolygon(p); public void fillPolygon(Polygon p); draw the filled polygon; use the current colour e.g. g.fillPolygon(p);

213 Polyline Method public abstract void drawPolyLine( int xs[], int ys[], int num); draw the polyline specified by the coordinates in xs[] and ys[]; num is the number of points if the last point is different from the first then the polyline is open continued

214 (20,20) (30,30) (20,40) e.g. int xs = {20,30,20}; int ys = {20,30,40}; g.drawPolyline(xs,ys,3);

215 Examples

216 8. Java 2D Java 2D was introduced in JDK 1.2. to deal with graphics weaknesses e.g. single-pixel thickness lines, limited fonts, poor shape manipulation (e.g. no rotation), no special fills/gradients/patterns inside shapes, poor image support

217 8.1. Using Java 2D Redefine paint() as before, but the graphics context must be cast to type Graphics2D before the Java 2D operations can be used. public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; : // call Java 2D methods on g2 }

218 8.2. Examples continued

219

220 8.3. More Information Beyond Java 2D Java 3D
Java 2D Graphics / Jonathan Knudsen O’Reilley, 1999 Beyond Java 2D Java 3D create 3D objects (e.g. boxes, spheres) build virtual worlds, controlled by Java! java-media/3D/ Java Advanced Imaging API (JAI) very sophisticated image processing java-media/jai/

221 AWT Controls Overview We list the AWT controls in two categories:
basic controls top-level containers

222 Basic Controls Control AWT Class Name button Button, CheckBox
choice Choice list List menu Menu, MenuBar, MenuItem text field TextField label Label text TextArea

223 Top-level Containers Container AWT Class Name frame Frame

224 Examples import java.applet.*;
import java.awt.* import java.applet.*; public class ButtApplet extends Applet { Button button1, button2, button3, button4; Public void init(){ button1=new Button(“button1”); button2=new Button(“button2”); button3=new Button(“button3”); button4=new Button(“button4”); add(button1); add(button2); add(button3); add(button4); }}

225 Swing GUI components In JDK 1.2 and later, GUI interfaces should be written with the Swing GUI components Swing includes buttons, text fields, scrolling windows, editor windows, tree displays, etc we will describe some of them

226 1.1. Swing and AWT In older Java programs, the AWT (Abstract Window Toolkit) GUI components are used Swing has replaced AWT GUIs never mix Swing and AWT GUIs in a single program Some parts of AWT are still used e.g. the layout managers continued

227 Swing supports lightweight GUI components
they are drawn onto the screen in an area controlled by Java the GUI is implemented completely within the JVM advantage: the 'look' of GUI components can be controlled by Java continued

228 AWT supports heavyweight GUI components
each Java GUI component is actually a simple layer hiding the OSes GUI component the OS component is called a peer component e.g. on Windows, a Java button in AWT is implemented using a Windows' button continued

229 1.2. Disadvantages of AWT Java does not have complete control over the AWT GUI components some JAVA AWT GUIs do not work because of problems with the underlying OS (e.g. file choosing in Windows) The "look and feel" of Java GUIs in AWT vary between OSes.

230 2. Three Steps to GUIs There are three main steps to creating a GUI for a Java program: 1. Declare the GUI controls; 2. Implement the event handlers for the controls; 3. Position the controls on the screen by using layout managers and/or containers.

231 2.1. Some Definitions Control a control is a GUI element
e.g. a button, textfield, scrollbar continued

232 Container a container is way of grouping controls (or other containers) this makes it simpler to move, hide, or show a group of controls, since the container can be manipulated 'top-level' containers in Java include JFrame and JApplet continued

233 Component Java uses the word 'component' to talk about controls and containers the Swing package supports GUI components, such as buttons, text fields (controls), and frames and applets (containers) The Swing implementation has every control and container inherit from JComponent

234 Basic Graphics Examples
// Graf1.java import javax.swing.*; import java.awt.*; public class Graf1 extends JApplet { public void paint(Graphics g) { // set the ‘foreground’ color g.setColor(Color.red); g.drawString("Hello", 25, 25); } } continued

235 Graf1. html: <html> <applet code="Graf1
Graf1.html: <html> <applet code="Graf1.class" width="200" height="100"> </applet> </html>

236 Use appletviewer Graf1.html

237 Graf2.java import javax.swing.*; import java.awt.*; import java.awt.event.*; // for window listener public class Graf2 extends JFrame { public Graf2() { super("Graf2"); setSize(200, 100); // includes title bar show(); } public void paint(Graphics g) { g.setColor(Color.red); g.drawString("Hello", 25, 50); // below title } :

238 public static void main(String args[]) { Graf2 gf2 = new Graf2();. gf2
public static void main(String args[]) { Graf2 gf2 = new Graf2(); gf2.addWindowListener( // anonymous class for window closing new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } // end of main() } // end of Graf2 class

239 Use java Graf2

240 ShowColors.java import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ShowColors extends JFrame { public ShowColors() { super( "Using colors" ); setSize( 400, 130 ); show(); } :

241 public void paint( Graphics g ) { // set new drawing color using integers g.setColor( new Color( 255, 0, 0 ) ); g.fillRect( 25, 25, 100, 20 ); g.drawString( "Current RGB: " g.getColor(), 130, 40 ); // set new drawing color using floats g.setColor( new Color( 0.0f, 1.0f, 0.0f ) ); g.fillRect( 25, 50, 100, 20 ); g.drawString( "Current RGB: " g.getColor(), 130, 65 ); :

242 // set new drawing color g. setColor( Color. blue ); g
// set new drawing color g.setColor( Color.blue ); g.fillRect( 25, 75, 100, 20 ); g.drawString( "Current RGB: " g.getColor(), 130, 90 ); // display individual RGB values Color c = Color.magenta; g.setColor( c ); g.fillRect( 25, 100, 100, 20 ); g.drawString( "RGB values: " + c.getRed() + ", " + c.getGreen() + ", " + c.getBlue(), 130, 115 ); } // end of paint() :

243 public static void main( String args[] ) { ShowColors app = new ShowColors(); app.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit( 0 ); } } ); } // end of main() } // end of ShowColors

244 Use

245 Fonts.java import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Fonts extends JFrame { public Fonts() { super( "Using fonts" ); setSize( 420, 125 ); show(); } :

246 public void paint( Graphics g ) { // set current font to Serif (Times), bold, // 12pt and draw a string g.setFont( new Font("Serif",Font.BOLD, 12)); g.drawString("Serif 12 point bold.",20,50); // set current font to Monospaced (Courier), // italic, 24pt and draw a string g.setFont( new Font("Monospaced",Font.ITALIC,24)); g.drawString( "Monospaced 24 point italic.", , 70 ); :

247 // set font to SansSerif (Helvetica), // plain, 14pt and draw a string g.setFont( new Font("SansSerif", Font.PLAIN, 14) ); g.drawString("SansSerif 14 pt plain.",20,90 ); // set font to Serif (times), bold/italic, // 18pt and draw a string g.setColor( Color.red ); g.setFont( new Font( "Serif", Font.BOLD + Font.ITALIC, 18 ) ); g.drawString( g.getFont().getName() + " " g.getFont().getSize() " point bold italic.", 20,110); } // end of paint() :

248 public static void main( String args[] ) { Fonts app = new Fonts(); app.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit( 0 ); } } ); } // end of main() } // end of Fonts

249 Use

250 LinesRectsOvals.java // Drawing lines, rectangles and ovals import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LinesRectsOvals extends JFrame { public LinesRectsOvals() { super( "Drawing lines, rectangles and ovals" ); setSize( 400, 165 ); show(); } :

251 public void paint( Graphics g ) { g. setColor( Color. red ); g
public void paint( Graphics g ) { g.setColor( Color.red ); g.drawLine( 5, 30, 350, 30 ); g.setColor( Color.blue ); g.drawRect( 5, 40, 90, 55 ); g.fillRect( 100, 40, 90, 55 ); g.setColor( Color.cyan ); g.fillRoundRect( 195, 40, 90, 55, 50, 50 ); g.drawRoundRect( 290, 40, 90, 55, 20, 20 ); g.setColor( Color.yellow ); g.draw3DRect( 5, 100, 90, 55, true ); g.fill3DRect( 100, 100, 90, 55, false ); g.setColor( Color.magenta ); g.drawOval( 195, 100, 90, 55 ); g.fillOval( 290, 100, 90, 55 ); } // end of paint() :

252 public static void main( String args[] ) { LinesRectsOvals app =
public static void main( String args[] ) { LinesRectsOvals app = new LinesRectsOvals(); app.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit( 0 ); } } ); } // end of main() } // end of LinesRectsOvals class

253 Use

254 Swing Controls Overview
We list the Swing controls in six categories: basic controls uneditable displays editable displays space-saving containers top-level containers other containers

255 Basic Controls Control Swing Class Name
button JButton, JCheckBox, JRadioButton combo box JComboBox list JList menu JMenu, JMenuBar, JMenuItem slider JSlider toolbar JToolbar text field JTextField, JPasswordField

256 Uneditable Displays Control Swing Class Name label JLabel
Tooltip JToolTip Progress bar JProgressBar

257 Editable Displays Control Swing Class Name table JTable
text JTextPane, JTextArea, JEditorPane tree JColorChooser file chooser JFileChooser

258 Space-saving Containers
Container Swing Class Name scroll pane JScrollPane, JScrollBar split pane JSplitPane tabbed pane JTabbedPane

259 Top-level Containers Container Swing Class Name frame JFrame
applet JApplet dialog JDialog, JOptionPane

260 Other Containers Container Swing Class Name panel JPanel
internal frame JInternalFrame layered pane JLayeredPane root pane JRootPane indirectly used by top-level containers to gain access to the content pane and other 'layers' of the container

261 JColorChooser JColorChooser is a SWING GUI for interactively selecting colours intended for applications where the user needs to select colours

262

263 Two GUI programs: LabelTest.java (an application) LabelTest2.java (an applet) They use the JLabel and JToolTip controls, which are uneditable, and so do not require event handlers event handlers will be explained in the next section continued

264 The layout manager is FlowLayout
explained later The application uses the top-level container JFrame. The applet uses the top-level container JApplet the most common containers

265 4.1. LabelTest.java step 1 step 2
// The JLabel GUI in a Java application import javax.swing.*; import java.awt.*; import java.awt.event.*; public class LabelTest extends JFrame { public LabelTest() { super( "Testing JLabel" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); : step 1 step 2

266 step 3 // JLabel with a string argument JLabel label1 = new JLabel( "Label with text" ); label1.setToolTipText( "This is label1" ); c.add( label1 ); // JLabel with string, Icon and alignment Icon bug = new ImageIcon( "bug1.gif" ); JLabel label2 = new JLabel( "Label with text and icon", bug, SwingConstants.LEFT ); c.add( label2 ); setSize( 200, 100 ); show(); } // end of LabelTest() step 4 step 5

267 public static void main( String args[] ) { LabelTest app = new LabelTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } // end of main() } // end of LabelTest class

268 Use

269 Notes The GUI is initialized in the class' constructor method: LabelTest(). Initialization steps: 1. get the container for the frame 2. set the layout manager (FlowLayout) 3. declare the controls 4. add them to the container 5. set the size of the window, and show it continued

270 Tooltip text can be added to all GUI controls.
label1.setToolTipText( "This is label1" ); Labels can be constructed in several ways: the second label includes an image and alignment information ImageIcon() is the standard way to load small images. continued

271 The frame (window) is created by calling its constructor inside main()
main() also adds an event handler to the frame it causes the program to exit when a 'window closing' event is output from the frame very common way to close a frame and exit more later

272 4.2. LabelTest2.java The applet version step 1 step 2
// The JLabel GUI in a Java applet import javax.swing.*; import java.awt.*; // import java.awt.event.*; // not needed public class LabelTest2 extends JApplet { public void init() { Container c = getContentPane(); c.setLayout( new FlowLayout() ); : step 1 step 2

273 step 3 // JLabel with a string argument JLabel label1 = new JLabel( "Label with text" ); label1.setToolTipText( "This is label1" ); c.add( label1 ); // JLabel with string, Icon and alignment Icon bug = new ImageIcon( "bug1.gif" ); JLabel label2 = new JLabel( "Label with text and icon", bug, SwingConstants.LEFT ); c.add( label2 ); } // end of init() } // end of LabelTest2 class step 4

274 LabelTest2.html <html> <body> <applet code="LabelTest2.class" width="200" height="100"> </applet> </body> </html>

275 Use c:> appletviewer LabelTest2.html

276 Notes The class extends JApplet not JFrame. There is no main().
There is no constructor method in the class, the initialization is done inside init() the usual place for GUI creation in applets continued

277 The initialization is similar, but a bit different:
1. get the container for the applet 2. set the layout manager (FlowLayout) 3. declare the controls 4. add them to the container but do not set the size of the window, or show it The size is set in LabelTest2.html, and the applet is displayed automatically. continued

278 There is no need for an event handler for closing the applet and exiting
that is done automatically Since the code has no event handlers, there is no need to import java.awt.event.* but in general applets do use event handlers (see later)

279 Event Handlers An event handler is a method that is called automatically when an event occurs in a GUI component. Examples of events include: typing return in a text field pressing a button clicking the mouse over a component continued

280 A listener class is an interface
Event handlers (methods) for different events are predefined by Java inside listener classes. A listener class is an interface it defines the interfaces of its event handler methods (i.e. the names, types of arguments) the programmer must implement each method to respond to the event that triggers it continued

281 Event Handler as a Diagram
class that implements the listener class Program on-screen GUI event event handler method data methods Program Code A typical action is for the event handler method to update the data back in the program.

282 Using Event Handlers The programmer must:
1. Implement the listener classes, by coding their event handler methods 2. 'Register' the GUI components in their program with the implemented listener classes The Java runtime system will automatically pass events to the handlers for processing.

283 Components and Events There are 10 Listener classes that can handle events from different GUI components ActionListener ItemListener MouseListener and MouseMotionListener WindowListener KeyListener TextListener ComponentListener ContainerListener FocusListener Not considered here

284 ActionListener It deals with events from:
JButton, JMenu, JMenuItem, JRadioButton, JCheckBox when a control is pressed JTextField when enter is typed The interface has one method: public void actionPerformed(ActionEvent e)

285 ItemListener It deals with events from: The interface has one method:
JButton, JMenu, JMenuItem, JRadioButton, JCheckBox when an item in the control is selected The interface has one method: public void itemStateChanged(ItemEvent e) Some GUI components generate multiple events

286 MouseListener It deals with mouse clicks over GUI components.
Its interface has 5 methods: public void mouseClicked(MouseEvent e) public void mousePressed(MouseEvent e) public void mouseReleased(MouseEvent e) public void mouseEntered(MouseEvent e) public void mouseExited(MouseEvent e) continued

287 MouseMotionListener For efficiency reasons, mouse movement events are dealt with by a separate listener. Its interface has 2 methods: public void mouseDragged(MouseEvent e) public void mouseMoved(MouseEvent e)

288 WindowListener It deals with events from: Its interface has 7 methods:
JDialog, JFrame, JWindow Its interface has 7 methods: public void windowOpened(WindowEvent e) public void windowClosing(WindowEvent e) public void windowClosed(WindowEvent e) public void windowIconified(WindowEvent e) public void windowDeiconified(WindowEvent e) public void windowActivated(WindowEvent e) public void windowDeactivated(WindowEvent e) We used this method in LabelTest.java

289 //Example import java.applet.Applet; import java.awt.Graphics;
import java.awt.event.MouseListener; import java.awt.event.MouseEvent; // a class which has some methods for dealing with mouse click events public class MyEvent extends Applet implements MouseListener { int mouseX = 20, mouseY = 40; // register a mouse events handler addMouseListener(this); } public void paint(Graphics g) { g.drawString("Clicked point: " + mouseX + " " + mouseY, mouseX, mouseY);

290 // the mouse button pressed and the released in one motion
public void mouseClicked(MouseEvent evt) { mouseX = evt.getX(); mouseY = evt.getY(); repaint(); } // when the mouse cursor enters a component public void mousePressed(MouseEvent evt) {} // when the mouse cursor later released public void mouseReleased(MouseEvent evt) {} // when the mouse cursor enteres a component public void mouseEntered(MouseEvent evt) {} // when the mouse cursor leaves a component public void mouseExited(MouseEvent evt) {}

291 Butt.java import java.applet.*; import java.awt.*;
import java.awt.event.*; public class Butt extends Applet implements ActionListener{ Button redbut, greenbut, bluebut; Color red = Color.red; Color green = Color.green; Color blue = Color.blue; Color current = red; public void init(){ redbut = new Button("red"); greenbut = new Button("green"); bluebut = new Button("blue"); add(redbut); add(greenbut); add(bluebut);

292 current = red; redbut.addActionListener(this); greenbut.addActionListener(this); bluebut.addActionListener(this); } public void actionPerformed(ActionEvent e){ if (e.getSource() == redbut){ redbut.setEnabled(false); greenbut.setEnabled(true); bluebut.setEnabled(true); if (e.getSource() == greenbut){ redbut.setEnabled(true); greenbut.setEnabled(false); current = green;

293 if (e.getSource() == bluebut){
redbut.setEnabled(true); greenbut.setEnabled(true); bluebut.setEnabled(false); current = blue; } repaint(); public void paint(Graphics g){ g.setColor(current); g.fillRect(100, 50, 200, 100);

294 Reducing Handler Coding
When we implement an interface (a listener class), we must implement all of the methods inside it. Even if we only want to use one method, we still have to give empty implementations for all the other methods a lot of boring work for some listener classes

295 Long Example public class MyClose implements WindowListener { public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { System.exit(0); } public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }

296 Use in LabelTest.java public static void main( String args[] ) { LabelTest app = new LabelTest(); app.addWindowListener( new MyClose() ); }

297 addWindowListener() is the way that the listener is registered with the frame:
app.addWindowListener(...); Any window events output by app (the frame) will go to the listener object it will only respond to a 'window closing' event

298 Existing Long Classes Java supplies predefined classes which implement the bigger listener classes called adapter classes These adapter classes contain empty methods for all the event handlers the programmer must inherit the adapter class, and override the method they want with their own definition

299 Existing Adapter Classes
WindowAdapter MouseAdapter and MouseMotionAdapter FocusAdapter ContainerAdapter ComponentAdapter KeyAdapter

300 WindowAdapter.java public abstract class WindowAdapter implements WindowListener { public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }

301 Using WindowAdapter public class MyClose2 extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } }

302 Use in LabelTest.java public static void main( String args[] ) { LabelTest app = new LabelTest(); app.addWindowListener( new MyClose2() ); }

303 Using an Anonymous Class
A common coding style is to subclass an adapter class as an anonymous class inside the program. This is the approach used in the original LabelTest.java main() defines an anonymous class that overrides windowAdapter continued

304 main() in LabelTest.java:
public static void main( String args[] ) { LabelTest app = new LabelTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } anonymous class continued

305 GUI Layout Objectives describe the basic layout managers for GUIs

306 Contents 1. A Reminder on GUI Creation 2. Flow Layout 3. Grid Layout
4. Border Layout 5. Box Layout 6. Combining Layouts

307 1. Reminder on GUI Creation
A reminder of the three steps in writing GUIs: 1. Declare the GUI controls; 2. Implement the event handlers for the controls; 3. Position the controls on the screen by using layout managers and/or containers.

308 1.1. Emphasis of this Part The examples in this part will concentrate on layout managers and the JPanel container step 3 Layout managers examined: FlowLayout, GridLayout, BorderLayout, BoxLayout, combining layouts

309 2. Flow Layout Components are added left-to-right
they are centered in the container (frame/applet) a new line is started when necessary Resizing the frame/applet may cause components to move to a new line.

310 FlowDemo.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FlowDemo extends JFrame { public FlowDemo() { super("E-Commerce Application"); Container c = getContentPane(); c.setLayout( new FlowLayout() ); :

311 JCheckBox jck1 = new JCheckBox("Downgrade dog to cat"); JCheckBox jck2 = new JCheckBox("Upgrade bike to car"); JCheckBox jck3 = new JCheckBox("Add speed package"); c.add( jck1 ); c.add( jck2 ); c.add( jck3 ); JButton jb1 = new JButton("place order"); c.add( jb1 ); JButton jb2 = new JButton("cancel"); c.add( jb2 ); JLabel jl = new JLabel(new ImageIcon("bmw.jpg")); c.add(jl); setSize(400,200); show(); } // end of FlowDemo()

312 public static void main(String[] args) { FlowDemo app = new FlowDemo(); app.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } // end of main() } // end of FlowDemo

313 Initial Appearance

314 After Resizing There is now space for all the
checkboxes and buttons on 1 line.

315 Notes By default, all the components on a line are centered
the alignment can be altered, e.g. c.setLayout( new FlowLayout( FlowLayout.RIGHT)); there is also FlowLayout.LEFT The component sizes are unchanged this is not true of some other layout managers

316 3. Grid Layout GridLayout places components in a grid, specified in terms of the number of rows and columns the spacing between the grid cells can also be specified The components are resized to fit the grid cell they appear inside doesn't look nice continued

317 The other change is to increase the vertical size of the frame:
GridDemo.java contains one major change from FlowDemo.java: c.setLayout( new GridLayout(3,2,10,7); 3 rows, 2 columns, 10 pixel horizontal spacing, 7 pixel vertical spacing The other change is to increase the vertical size of the frame: setSize(400,400);

318 GridDemo.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GridDemo extends JFrame { public GridDemo() { super("E-Commerce Application"); Container c = getContentPane(); // use GridLayout: 3 rows, 2 columns // 10 pixel horiz. gap, 7 pixel vert. gap c.setLayout( new GridLayout(3, 2, 10, 7) ); :

319 JCheckBox jck1 = new JCheckBox("Downgrade dog to cat"); JCheckBox jck2 = new JCheckBox("Upgrade bike to car"); JCheckBox jck3 = new JCheckBox("Add speed package"); c.add( jck1 ); c.add( jck2 ); c.add( jck3 ); JButton jb1 = new JButton("place order"); c.add( jb1 ); JButton jb2 = new JButton("cancel"); c.add( jb2 ); JLabel jl = new JLabel(new ImageIcon( bmw.jpg")); c.add(jl); setSize(400,400); // extra depth (200 --> 400) show(); } // end of GridDemo()

320 public static void main(String[] args) { GridDemo app = new GridDemo(); app.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } // end of main() } // end of GridDemo

321 Appearance Components have been resized to equally fill the 400x400
space. Note the horizontal and vertical spacing between the components.

322 GridDemoP.java Components can be protected from resizing by being placed inside a JPanel the panel is resized instead : // use a panel to stop the cancel button growing JPanel p = new JPanel(); JButton jb2 = new JButton("cancel"); p.add(jb2); c.add( p ); :

323 Appearance the 'cancel' button has not been resized

324 4. Border Layout BorderLayout allows four components to be placed around the edges of a frame/applet, with a fifth component in the center the positions are "North", "East", "South", "West", and "Center" BorderLayout is the default layout for JFrame and JApplet

325 BorderDemo.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BorderDemo extends JFrame { public BorderDemo() { super("E-Commerce Application"); Container c = getContentPane(); // use BorderLayout: // 10 pixel horiz. gap, 7 pixel vert. gap c.setLayout( new BorderLayout(10, 7) ); :

326 // JCheckBox jck1 = new JCheckBox("Downgrade dog to cat"); JCheckBox jck2 = new JCheckBox("Upgrade bike to car"); JCheckBox jck3 = new JCheckBox("Add speed package"); c.add( jck2, "East" ); c.add( jck3, "South" ); JButton jb1 = new JButton("place order"); c.add( jb1, "North" ); JButton jb2 = new JButton("cancel"); c.add( jb2, "West" ); JLabel jl = new JLabel(new ImageIcon("bmw.jpg")); c.add(jl, "Center"); setSize(400,400); // extra depth (200 --> 400) show(); // pack(); // get rid of excess space } // end of BorderDemo()

327 public static void main(String[] args) { BorderDemo app = new BorderDemo(); app.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } // end of main() } // end of BorderDemo

328 Appearance Components have been Note the vertical resized to fill the
400x400 space. Note the vertical and horizontal spacing between the components

329 Component Resizing Components are resized:
North and South are stretched to be as wide as the window East and West are stretched to be tall enough to touch the North and South components Center is enlarged to be as big as possible Often the look of the GUI can be improved by calling pack() after show().

330 Appearance with pack()
The vertical and horizontal spacing between the components is not affected.

331 More than Five? It is possible to have more than five components in a GridLayout place them inside a JPanel (which can have its own layout) the JPanel container can become one of the components in the top-level frame/applet This use of JPanel is shown later.

332 Less than Five? If the grid does not have a component for a given position, then the other components are resized to fill the space. e.g. if North or South are not used, then East, Center, and West will be made taller to fill the space

333 5. Box Layout This places the components in a horizontal or vertical sequence components are not resized BoxDemo.java places its components vertically aside from the layout manager, the code is very similar to FlowDemo.java pack() can be used to reduce the window size

334 BoxDemo.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BoxDemo extends JFrame { public BoxDemo() { super("E-Commerce Application"); Container c = getContentPane(); // use BoxLayout: align components vertically c.setLayout( new BoxLayout(c, BoxLayout.Y_AXIS) ); :

335 JCheckBox jck1 = new JCheckBox("Downgrade dog to cat"); JCheckBox jck2 = new JCheckBox("Upgrade bike to car"); JCheckBox jck3 = new JCheckBox("Add speed package"); c.add( jck1 ); c.add( jck2 ); c.add( jck3 ); JButton jb1 = new JButton("place order"); c.add( jb1 ); JButton jb2 = new JButton("cancel"); c.add( jb2 ); JLabel jl = new JLabel(new ImageIcon("bmw.jpg")); c.add(jl); setSize(400,400); // extra depth (200 --> 400) show(); // pack(); // get rid of excess space } // end of BoxDemo()

336 public static void main(String[] args) { BoxDemo app = new BoxDemo(); app.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } // end of main() } // end of BoxDemo

337 Appearance

338 With pack()

339 6. Combining Layouts Real GUIs usually require several layout managers for different parts of the display. The basic technique is to create panels (with JPanel) to hold parts of the display each panel will have its own layout a panel may have subpanels

340 Example Appearance

341 Component Layout Hierarchy
frame (border) East West Center panel p1 (vertical box) panel p2 (vertical box) image check box check box check box button button

342 CombinedDemo.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CombinedDemo extends JFrame { public CombinedDemo() { super("E-Commerce Application"); Container c = getContentPane(); // use default BorderLayout for frame :

343 // panel 1: vertical box layout JPanel p1 = new JPanel(); p1
// panel 1: vertical box layout JPanel p1 = new JPanel(); p1.setLayout( new BoxLayout(p1, BoxLayout.Y_AXIS)); JCheckBox jck1 = new JCheckBox("Downgrade dog to cat"); JCheckBox jck2 = new JCheckBox("Upgrade bike to car"); JCheckBox jck3 = new JCheckBox("Add speed package"); p1.add( jck1 ); p1.add( jck2 ); p1.add( jck3 ); :

344 // panel 2: vertical box layout JPanel p2 = new JPanel(); p2
// panel 2: vertical box layout JPanel p2 = new JPanel(); p2.setLayout( new BoxLayout(p2, BoxLayout.Y_AXIS)); JButton jb1 = new JButton("place order"); p2.add( jb1 ); JButton jb2 = new JButton("cancel"); p2.add( jb2 ); :

345 JLabel jl = new JLabel(. new ImageIcon( "bmw
JLabel jl = new JLabel( new ImageIcon( "bmw.jpg")); // add panels and image to frame c.add(jl, "Center"); c.add(p1, "West"); c.add(p2, "East"); setSize(400,400); // extra depth (200 --> 400) show(); pack(); // remove excess space } // end of CombinedDemo()

346 public static void main(String[] args) { CombinedDemo app = new CombinedDemo(); app.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } // end of main() } // end of CombinedDemo

347 Multimedia Objectives introduce Java multimedia:
images, audio, animations

348 Contents 1. Images 2. Audio 3. Animations 4. Animation Issues in AWT
5. Image Download Problem 6. Applet Parameters 7. Image Maps 8. Beyond Basic Multimedia

349 Loading Images URL imageURL =
newURL("http://www.prenhall.com/logo.gif"); java.awt.Image img = this.getImage(imageURL); You can compress this into one line as follows Image img = this.getImage(new URL("http://www.rss.gov.jo/logo.gif")); Loading Images Images displayed by Java applets are retrieved from the web via a URL that points to the image file. An applet that displays a picture must have a URL to the image its going to display.Images can be stored on a web server, a local hard drive or anywhere else the applet can point to via a URL.Make sure you put your images somewhere the person viewing the applet can access them.Typically you'll put images in the same directory as either the applet or the HTML file. If you know the exact URL for the image you wish to load, you can load it with the getImage() method.The getImage() method is provided by java.applet.Applet.The URL class is provided by java.net.URL. Be sure to import it.

350 Notes Graphics formats supported: returns the location as a URL object
getDocumentBase() returns the location as a URL object can be on the Internet or in a local directory Graphics formats supported: GIF (Graphics Interchange Format) best for line drawings, black and white images JPEG (Joint Photographic Experts Group) best for full-colour photos

351 Retrieving an Image Both getImage() and ImageIcon() can be passed URLs, to download an image from the Web. Both methods return immediately, and they download the image in a separate (hidden) thread.

352 Drawing an Image requires an ImageObserver object
g.drawImage(Image, X, Y, ImageObserver) g.drawImage(Image, X, Y, width, height, ImageObserver) requires an ImageObserver object

353 ImageObserver The drawing of an image is controlled by an ImageObserver object. the ImageObserver object updates the drawing of the image as it is downloaded over the network, downloading may be slow which means the image will appear bit-by-bit g.drawImage(logo1, 0, 0, this); this is the JApplet, an ImageObserver object that draws to the screen

354 Drawing an ImageIcon scaling is not possible
ImageIcon.paintIcon( Component-holding-the-image, Graphics-object, X, Y) scaling is not possible no ImageObserver is needed ImageIcons can be converted to images (and then scaled) over the network, downloading may be slow which means the image will appear bit-by-bit

355 1. Images The tasks of LoadImageAndScale.java:
draw three images in an applet an image, full-size and scaled an ImageIcon

356 1.1. Usage Full-size Image ImageIcon Scaled Image

357 1.2. LoadImageAndScale.java
import java.applet.Applet; import java.awt.*; import javax.swing.*; public class LoadImageAndScale extends JApplet { private Image logo1; private ImageIcon logo2; public void init() { logo1 = getImage( getDocumentBase(), "logo.gif" ); logo2 = new ImageIcon( "logo.gif" ); }

358 public void paint( Graphics g ) { // draw the original image g
public void paint( Graphics g ) { // draw the original image g.drawImage( logo1, 0, 0, this ); // draw image scaled to fit width of applet // and height of applet minus 120 pixels g.drawImage( logo1, 0, 120, getWidth(), getHeight() - 120, this ); // draw icon using its paintIcon method logo2.paintIcon( this, g, 180, 0 ); } } // end of LoadImageAndScale

359 LoadImageAndScale.html <html> <applet code="LoadImageAndScale.class" width=340 height=340> </applet> </html>

360 2. Audio Sounds can be played with the Applet play() methods: Methods:
load the sound, play it once only Methods: public void play(URL u, String fname); public void play(URL u); continued

361 For example: play( getDocumentBase(), “hi.au”); play “hi.au” after loading it from the same place as the Web page

362 2.1. AudioClip Sounds A more flexible way of playing sounds is to use AudioClip methods. Methods for loading: public void getAudioClip(URL u, String fname); public void getAudioClip(URL u); continued

363 Methods for playing: public void play(); play the audio clip once
public void loop(); play the audio clip repeatedly public void stop(); stop playing the audio clip

364 2.2. Audio Example Load and play a AudioClip
looping playing is possible playing can be stopped

365 Event Model Play Loop Stop currentSound ItemStateChanged(...) {... }
anon. class ActionPerformed(...) {... } ButtonHandler

366 LoadAudioAndPlay.java // Load an audio clip and play it. import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LoadAudioAndPlay extends JApplet { private AudioClip sound1, sound2, currentSound; private JButton playSound, loopSound, stopSound; private JComboBox chooseSound; public void init() { Container c = getContentPane(); c.setLayout( new FlowLayout() ); String choices[] = { "Welcome", "Hi" }; chooseSound = new JComboBox( choices ); :

367 chooseSound.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { currentSound.stop(); currentSound = chooseSound.getSelectedIndex() == 0 ? sound1 : sound2; } } ); c.add( chooseSound ); :

368 ButtonHandler handler = new ButtonHandler(); playSound = new JButton( "Play" ); playSound.addActionListener( handler ); c.add( playSound ); loopSound = new JButton( "Loop" ); loopSound.addActionListener( handler ); c.add( loopSound ); stopSound = new JButton( "Stop" ); stopSound.addActionListener( handler ); c.add( stopSound ); sound1 = getAudioClip( getDocumentBase(), "welcome.wav" ); sound2 = getAudioClip( getDocumentBase(), "hi.au" ); currentSound = sound1; } // end of init()

369 // stop sound when user switches Web pages // (i. e
// stop sound when user switches Web pages // (i.e., be polite to the user) public void stop() { currentSound.stop(); } private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if ( e.getSource() == playSound ) currentSound.play(); else if ( e.getSource() == loopSound ) currentSound.loop(); else if ( e.getSource() == stopSound ) currentSound.stop(); } } // end of ButtonHandler class } // end of LoadAudioAndPlay class

370 LoadAudioAndPlay.html <html> <applet code="LoadAudioAndPlay.class" width=350 height=50> </applet> </html>

371 2.3. Notes Audio formats supported: au (Sun Audio) wav (Windows Wave)
aif / aiff (Macintosh AIFF) MIDI (Musical Instrument Digital Interface)

372 3. Animations 3.1. A Simple Animation 3.2. Event Model 3.3. Usage
3.4. Timers 3.5. LogoAnimator.java 3.6. Notes

373 3.1. A Simple Animation Load a series of ImageIcons into an array.
Display the ImageIcons in a JPanel (acting as a canvas) each image is displayed by redrawing JPanel after incrementing an array index counter the redrawing freqency is controlled by a timer

374 3.2. Event Model app JFrame timer LogoAnimator JPanel
paintComponent(...) { ... } actionPerformed(...) { repaint();} timer LogoAnimator JPanel

375 3.3. Usage

376 3.4. Timers A Timer object can output ActionEvents at regular time intervals these events will trigger actionPerformed() in the specified object Setting a Timer Timer foo = new Timer(frequency, object-receiving-events); continued

377 foo.start(); // start the timer
foo.stop(); // stop it foo.restart(); // restart after a stop foo.isRunning(); // boolean test

378 3.5. LogoAnimator.java // Animation a series of images import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LogoAnimator extends JPanel implements ActionListener { protected ImageIcon images[]; protected int totalImages = 30, currentImage = 0, animationDelay = 50; // ms delay protected Timer animationTimer; :

379 A 'problem' with ImageIcon() is that it returns before it
finishes loading. public LogoAnimator() { setSize( getPreferredSize() ); images = new ImageIcon[ totalImages ]; // load the images into the array for ( int i = 0; i < images.length; ++i ) images[ i ] = new ImageIcon( "images/deitel" + i ".gif" ); startAnimation(); } continued

380 public void startAnimation() { if ( animationTimer == null ) { currentImage = 0; animationTimer = new Timer( animationDelay, this ); animationTimer.start(); } else // continue from last image displayed // should not be used in this example if ( ! animationTimer.isRunning() ) animationTimer.restart(); } public void stopAnimation() // not used in this example { animationTimer.stop(); } continued

381 Check if the image has been loaded.
public void actionPerformed( ActionEvent e ) { repaint(); } public void paintComponent( Graphics g ) // redraw the panel { super.paintComponent( g ); if (images[currentImage].getImageLoadStatus() == MediaTracker.COMPLETE ) { images[currentImage].paintIcon( this, g, 0, 0 ); currentImage = (currentImage + 1) % totalImages; } } Check if the image has been loaded. continued

382 public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getPreferredSize() { return new Dimension( 160, 80 ); } continued

383 public static void main( String args[] ) { LogoAnimator anim = new LogoAnimator(); JFrame app = new JFrame( "Animator test" ); app.getContentPane().add( anim, BorderLayout.CENTER ); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); app.setSize( anim.getPreferredSize().width + 10, anim.getPreferredSize().height + 30 ); app.show(); } } // end of LogoAnimator

384 3.6. Notes Component Sizes JPanel (and other controls and components) support the methods getMinimumSize() and getPreferredSize() defining them allows the layout manager to automatically obtain size information about the component

385 paintComponent() paint() redraws a top-level container (e.g. JFrame, JApplet) paintComponent() is used to redraw other containers (e.g. JPanel) The programmer redefines paintComponent() in the same way as paint() it will be called by repaint() continued

386 but only if the ImageIcon has been fully loaded
paintComponent() is redefined to paint an ImageIcon from the array but only if the ImageIcon has been fully loaded if (images[currentImage].getImageLoadStatus() == MediaTracker.COMPLETE ) { ...}

387 4. Beyond Basic Multimedia
Some other Java Media APIs: Java 2D, Java 3D, Java Advanced Imaging, Java Media Framework (JMF), Java Sound, Java Speech More details: java-media/

388 4.1. JMF 2.1 Capture, playback, transmit and translate audio, video and other media Some supported formats: AVI, GSM, MPEG-1, QuickTime, RMF, RTP, Vivo, etc. More details: java-media/jmf/index.html

389 4.2. Java Sound Provides low-level support for audio operations such as audio mixing, audio capture, MIDI sequencing, and MIDI synthesis More details: java-media/sound/index.html

390 4.3. Java Speech (JSAPI) Specifies a cross-platform interface to support speech recognizers, dictation systems, speech synthesizers, etc. Related work: Java Speech API Markup Language (JSML) Java Speech API Grammar Format (JSGF) More details: java-media/speech/index.html

391 Input/Output Objectives discuss stream I/O in Java

392 Contents 1. Two Common Data Formats 2. Java I/O Essentials
3. Predefined Streams 4. Forms of Input 5. Forms of Output

393 1. Two Common Data Formats
ASCII a 8-bit code (1 char = 1 byte) it can only represent 256 different chars Unicode a 16-bit code (1 char = 2 bytes) it can represent 65,536 different chars good for many non-English character sets

394 2. Java I/O Essentials All I/O in Java is done using streams.
There are two kinds of streams: 8-bit streams, 16-bit streams The 8-bit streams are known as: InputStreams, OutputStreams The 16-bit streams are known as: Readers (for input), Writers (for output) Class names for I/O almost always contain the words Reader, Writer, InputStream, or OutputStream this helps you identify what they can do

395 3. Predefined Streams System.in
an InputStream used to read bytes from the keyboard System.out a PrintStream used to write bytes to the screen System.err a separate PrintStream (useful for redirection)

396 4. Forms of Input We will consider the following input techniques:
reading characters from the keyboard/file reading binary data from a file reading numbers and other types from the keyboard

397 Classes for Input Data Format Class to use ASCII / Unicode System.in (keyboard input) FileReader (file input) InputStreamReader (byte stream, e.g. network) Binary DataInputStream Object ObjectInputStream

398 4.1. Reading Chars from the Keyboard
The basic method is read() in System.in int read() throws IOException returns a unicode value, or -1 to signal end of stream ASCII input is converted to Unicode read() must be in a try-catch block

399 Example: readin.java import java.io.*; public class readin { public static void main(String args[]) { int i; try { while ( (i = System.in.read()) != -1 ) System.out.println( "read char: " + (char) i +" hex value: " +Integer.toString(i,16)); } catch (IOException ioe) { System.out.println( "IO error:" + ioe ); } } } // end of readin class

400 Usage I typed hello, enter, then ctrl-Z in Windows, enter
C> java readin hello read char: h hex value: 68 read char: e hex value: 65 read char: l hex value: 6c read char: l hex value: 6c read char: o hex value: 6f hex value: d read char: hex value: a C> in Windows, enter is represented by carriage return ('\r'), linefeed ('\n')

401 4.2. Reading Chars from a File
The basic method is read() in FileReader int read() throws IOException The FileReader constructor takes the name of a file: FileReader fr = new FileReader("filename"); the file is automatically openned Files should be closed with close().

402 Example: fileread.java
import java.io.*; public class fileread { public static void main(String args[]) { int i; int bytesRead = 0; try { FileReader fr = new FileReader("animals.txt"); while ( (i = fr.read()) != -1 ) bytesRead++; fr.close(); } catch (IOException ioe) { System.out.println( "IO error:" + ioe ); } System.out.println("bytes read from file: " +bytesRead); } } It counts the number of bytes

403 Usage C> cat animals.txt queenbee raven swan terrier urchin vixen wallaby xoachi yellowjacket zebra C> java fileread bytes read from file: 77 C>

404 4.3. Reading from a Binary File
DataInputStream is intended to read binary data from a stream and return it in the specified data format. Some of its methods: boolean readBoolean() int readInt() float readFloat() byte readByte() Unlike read() in System.in and FileReader, the methods do not return -1 at the end of the stream/file. instead an EOFException is raised your code must catch this in order to stop reading

405 DataInputStream expects binary data coming from a stream
to read binary data from a file requires stream layering with FileInputStream int FileInputStream DataInputStream Binary File float bytes from a file bytes from a stream etc.

406 Example: readdata.java
import java.io.*; public class readdata { public static void main(String args[]) { FileInputStream fis; DataInputStream dis; try { fis = new FileInputStream( args[0] ); dis = new DataInputStream( fis ); System.out.println( "input file: " args[0] ); :

407 for binary stream input
An infinite loop is the common coding style for binary stream input int i; while ( true ) { // eof is an exception i = dis.readInt(); System.out.println( "read: " + i ); } } catch (EOFException eof) { System.out.println( "EOF reached " ); } catch (IOException ioe) { System.out.println("IO error: " +ioe); } } } // end of readdata class This catch block must be coded.

408 5. Forms of Output We will consider the following output techniques:
writing data to the screen writing characters to a file formatted character output writing data to a binary file

409 Classes for Output Data Format Class to use ASCII / Unicode System.out (screen output) FileWriter (output to file) OutputStreamWriter (byte stream, e.g. network) Binary DataOutputStream Object ObjectOutputStream

410 Writing Data to the Screen / Writing Chars to a File
System.out.println(...) System.out.print(...); they take a variety of data types, and output them as strings Use FileWriter methods: void write(String s); void write(int i); etc. void flush(); void close(); The FileWriter constructor takes the name of a file: FileWriter fw = new FileWriter("filename"); the file is automatically openned

411 Example: filewrite.java
import java.io.*; public class filewrite { public static void main(String args[]) { FileWriter fw; int i; try { fw = new FileWriter( args[0] ); while ( (i = System.in.read()) != -1 ) fw.write( (char) i ); fw.close(); } catch (IOException ioe) { System.out.println( "IO error:" + ioe ); } } }

412 Usage I typed this, enter, and ctrl-Z
C> java filewrite foo.txt hello Daher C> type foo.txt hello Daher C> I typed this, enter, and ctrl-Z

413 Writing to a Binary File
DataOutputStream is intended to write data to a binary stream. Some of its methods: void writeInt(int) void writeFloat(float) void writeBoolean(boolean) void writeByte(int) continued

414 DataInputStream streams can read anything output by a DataOutputStream
Layered streams are needed to connect a DataOutputStream to a binary file. int FileOutputStream DataOutputStream Binary File float bytes to a file bytes in a stream etc.

415 Example: writedata.java
import java.io.*; public class writedata { public static void main(String args[]) { FileOutputStream fos; DataOutputStream ds; try { fos = new FileOutputStream(args[0]); ds = new DataOutputStream( fos ); int a[] = {0,1,2,3,4,5,6,7,8,9}; for (int i=0; i<a.length; i++) ds.writeInt(a[i]); ds.close(); } catch (IOException ioe) { System.out.println( "IO error: "+ioe); } } }

416 Usage create the binary file read it back in
C>java writedata numbers.txt C>java readdata numbers.txt input file: numbers.txt read: 0 read: 1 read: 2 read: 3 read: 4 read: 5 read: 6 read: 7 read: 8 read: 9 EOF reached C> read it back in


Download ppt "Java Programming E-mail: daher@rss.gov.jo Daher Thabit Daher Chief Architect E-mail: daher@rss.gov.jo."

Similar presentations


Ads by Google