Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming Daher Thabit Daher Chief Architect

Similar presentations


Presentation on theme: "Java Programming Daher Thabit Daher Chief Architect"— Presentation transcript:

1 Java Programming 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.

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 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 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 continued JSDK 1.3 for Windows

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

12 Java Advantages Productivity –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 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 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’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) Java Disadvantages

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 code (.java file) javac (Pentium) javac (Mac) javac (UNIX) Java bytecode (.class file) Java runtime (Pentium) Java runtime (Mac) Java runtime (UNIX)

20 The Java Platform  The Java Virtual Machine (Java VM)  The Java Application Programming Interface (Java API)

21 Java Program Structure Basic syntax of a Java class: class { }

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

23 Declaring Attributes [= ]; 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”; }

24 Declaring Methods ( ){ 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; }}

25 Access Control ModifierSame classSame PackageSubclassUniverse publicYes protectedYes defaultYes privateYes 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.

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.. ; Examples: import java.util.list; import java.io.*; import java.sql.*;

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

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)

34 Data Types

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;

36 Variables Variable Declaration int myInteger; Variable Initialization myInteger = 10; int count = 0; Final Variables (constants) final int aFinalVariable = 0;

37 Operators Unary operators, ex. ++ –prefix or postfix notation operator operand or operand operator Binary operators, ex. = –infix notation operand1 operator operand2 Tertiary operator ?: –infix notation expression ? Operand1 : operand2

38 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

39 Arithmetic Operators

40 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 If count currently contains 45, then total = ++count; assigns the value 46 to both total and count

42 Relational Operators

43 Bitwise Operators

44 Assignment Operators

45 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

47 Operator Precedence

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

49 49 The if/else Statements if (expression) { statement(s) } if (response == OK) { // code to perform OK action } else { // code to perform Cancel action }

50 50 The switch Statement The syntax of the switch statement is: switch (expression) { case value1: statement-list1 case value2: statement-list2 case … }

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

53 53 The do Statement statement condition false true The do statement has the following syntax: do statement while (condition);

54 54 The for Statement The syntax of the for loop is for (intialization; condition; increment) statement; which is equivalent to initialization; while (condition) { statement; increment; }

55 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 ).

56 Control.java 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();

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

61 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 scores

62 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

63 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'};

64 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

65 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

66 66 Multidimensional Arrays

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

68 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 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.

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 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 Four different ways (there are more).

72 Comparing Strings 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 AZaz continued

73 s1.compareTo(s2) –returns 0 if s1 and s2 are equal –returns 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 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”) for text analysis

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

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

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."); System.out.println("x = " + x); System.out.println("y = " + y); }

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. class [extends ] { }

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

92 class MyPoint { public void display() { System.out.println("display() in MyPoint."); } class Derived extends MyPoint { // overriding display() method of the superclass public void display() { 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) { statement(s) } finally { statement(s) }

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

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

105 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

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 connectivity data processing utilities JDBC driver for Oracle 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 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: –first(), last(), next(), previous(), etc. Typical code: while( rs.next() ) { // process the row; } Daher Sirin Emad Odeh cursor

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.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.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 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 executeUpdate()

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 = { "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.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.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 Objectives –describe basic threads in Java Threads

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 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 // The two ways to obtain a thread of code // 1. extend class Thread // 2. 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.Thread public void run() { for(int i = 0; i < 300; i++) System.out.println(i + ". Extension of THREAD running"); } } class SimpRunnable implements Runnable { // 2. implement the Runnable interface, public void run() { for (int i = 0; i < 300; i++) System.out.println(i + ". Implem. of RUNNABLE running"); } }

145 Usage $ 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 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(); } } A thread and a Runnable object that both sleep

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

150 Usage 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 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 continued good bad

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 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 Using yield() to improve fairness in Window

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 $ 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 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 $ 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 : with the yield() calls in The three threads start together tea thread finishes continued

163 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: 0 0 (X,Y) X axis Y axis +y +x note

167 Coordinate

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 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 repaint()

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

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

179 Java Applets Java source code Java bytecode Java compiler Java interpreter Web browser

180 MyApplet.java import java.applet.*; import java.awt.*; public class MyApplet extends Applet { public void paint(Graphics g) { ……………….; ………………..; }

181 Simple HTML document My First Applet

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 }

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

184 Applet Life Cycle public void init(); public void start(); public void stop(); public void destroy();

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.

187 Predefined Colors ColorRGB triple public final static Color orange255,200,0 public final static Color pink255,175,175 public final static Color black0,0,0 public final static Color white255,255,255 public final static Color red255,0,0 public final static Color green0,255,0 public final static Color blue0,0,255 :

188 Common Colors Color.lightGray Color.magenta Color.orange Color.pink Color.red Color.white Color.yellow Color.black Color.blue Color.cyan Color.darkGray Color.gray Color.green

189 Color Methods 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 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: –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 Serif Monospaced SansSerif

194 Lines, Rectangles, Ovals 1. Lines 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); }

196 2. Rectangles 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 (x,y)width height

197 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 rectangle window

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

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

200 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 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) width height 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 0 degrees (x,y) height width continued starting angle ending angle

206 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 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); a positive number means “positive sweep”; negative means “negative sweep”

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 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); (20,20) (30,30) (20,40)

213 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 Polyline Method continued

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

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 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! –http://java.sun.com/products/ java-media/3D/ Java Advanced Imaging API (JAI) –very sophisticated image processing –http://java.sun.com/products/ java-media/jai/

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

222 Basic Controls ControlAWT Class Name –buttonButton, CheckBox –choice Choice –listList –menuMenu, MenuBar, MenuItem –text field TextField –label Label –text TextArea

223 Top-level Containers ContainerAWT Class Name –frameFrame

224 Examples 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:

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.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.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.", 20, 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.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 = 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 ControlSwing Class Name –buttonJButton, JCheckBox, JRadioButton –combo boxJComboBox –listJList –menuJMenu, JMenuBar, JMenuItem –sliderJSlider –toolbarJToolbar –text fieldJTextField, JPasswordField

256 Uneditable Displays ControlSwing Class Name –labelJLabel –TooltipJToolTip –Progress barJProgressBar

257 Editable Displays ControlSwing Class Name –tableJTable –textJTextPane, JTextArea, JEditorPane –treeJColorChooser –file chooserJFileChooser

258 Space-saving Containers ContainerSwing Class Name –scroll paneJScrollPane, JScrollBar –split paneJSplitPane –tabbed paneJTabbedPane

259 Top-level Containers ContainerSwing Class Name –frameJFrame –appletJApplet –dialogJDialog, JOptionPane

260 Other Containers ContainerSwing Class Name –panelJPanel –internal frame JInternalFrame –layered paneJLayeredPane –root paneJRootPane 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 // 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 // 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 3 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 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 Notes

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 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() ); : The applet version step 1 step 2

273 // 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 3 step 4

274 LabelTest2.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 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 Program on-screen GUI Program Code data methods class that implements the listener class event event handler method 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: –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: –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); current = red; } if (e.getSource() == greenbut){ redbut.setEnabled(true); bluebut.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 public static void main( String args[] ) { LabelTest app = new LabelTest(); app.addWindowListener( new MyClose() ); } Use in LabelTest.java

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 ); } } ); } continued anonymous class

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 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 Note the horizontal and vertical spacing between the components. Components have been resized to equally fill the 400x400 space.

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 Note the vertical and horizontal spacing between the components Components have been resized to fill the 400x400 space.

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 Center West panel p1 (vertical box) image panel p2 (vertical box) check box check box check box 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.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.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.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"));

350 Notes 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 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 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 ImageIcon Scaled Image Full-size 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.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

360 2. Audio Sounds can be played with the Applet play() 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 PlayLoopStop 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., 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

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 paintComponent(...) {... } actionPerformed(...) { repaint();} timer LogoAnimator JPanel app JFrame

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 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 A 'problem' with ImageIcon() is that it returns before it finishes loading.

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 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; } } continued Check if the image has been loaded.

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 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: –http://java.sun.com/products/ 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: –http://java.sun.com/products/ 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: –http://java.sun.com/products/ 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: –http://java.sun.com/products/ java-media/speech/index.html

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

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: –InputStream s, OutputStream s The 16-bit streams are known as: –Reader s (for input), Writer s (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 FormatClass 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 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> I typed hello, enter, then ctrl-Z 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 Binary File bytes from a file bytes from a stream int float etc. FileInputStreamDataInputStream

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 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 An infinite loop is the common coding style for binary stream input 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 FormatClass 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 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. Binary File bytes to a file bytes in a stream int float etc. FileOutputStreamDataOutputStream

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

416 Usage 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> create the binary file read it back in


Download ppt "Java Programming Daher Thabit Daher Chief Architect"

Similar presentations


Ads by Google