Professional Documents
Culture Documents
Java Programming
Java Programming
continued
• February 1997: JDK v.1.1 released
– major changes in the event model used by the GUI;
inner classes introduced
continued
• JSDK contains all the libraries (packages),
compiler, and other tools for
writing/running/debugging Java code.
continued
Update Autoexec.bat
• Add the bin path for Java to the PATH
environment variable:
set PATH=%PATH%;c:\jdk1.3.0_02\bin
continued
• 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
• Portablility / Platform Independence
– “write once; run anywhere”
continued
• 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,WSAD4.0-5.0
– do not use them when first learning Java
• Good for teaching computing
– many important ideas in one place
• It’s new!
continued
Java Disadvantages
• Java’s security restrictions makes some
code hard to write:
– cannot “see” much of a local machine
• Slow Internet connections
– makes it difficult to download medium/large
applets
• Lots to learn
– Java language (small) and Java libraries
(very large)
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
Java Bytecodes
• The Java compiler (javac) generates
bytecodes
– a set of instructions similar to machine code
– not specific to any machine architecture
Java runtime
(Mac)
javac (Mac)
Java code Java bytecode
(.java file) (.class file)
Java runtime
javac (UNIX) (UNIX)
The Java Platform
The Java Virtual Machine (Java VM)
The Java Application Programming Interface
(Java API)
Java Program Structure
• Basic syntax of a Java class:
<modifier> class <name>
{
<attribute_declaration>
<constractor_declaration>
<method_declaration>
}
HelloWorld.java
class HelloWorld {
public static void main (String args [])
{
System.out.println (“Hello World “);
}
}
Declaring Attributes
<modifier> <type> <name> [=<default_value>];
type:byte-short-int-long-char-float-double,boolean .
• Examples:
Public class DeclarAttribute {
public int x;
private float y =1000.0;
private String name =“Daher Thabit”;
}
Declaring Methods
<modifier> <return_type> <name>(<parameter>){
statements;
}
Parameter : (parameter_type parameter_name)
Examples:
public class Thing {
private int x;
public int getX(){
return x;
}
public void setX(int new_x){
x = new_x;
}}
Access Control
Modifier Same class Same Package Subclass Universe
private Yes
java.applet java.net
java.awt java.rmi
java.beans java.security
java.io java.sql
java.lang java.text
java.math java.util
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
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
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)
Data Types
Type Size/Format Description
integral
byte 8-bit two's complement Byte-length integer
40
Example
If count currently contains 45, then
total = count++;
assigns 45 to total and 46 to count
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
45
Expressions
count++;
Order of evaluation may matter
x * y * z // Order is unimportant
x + y / 100 // Order is important here
Operator Precedence
Operator
Category Operators
postfix operators [] . (params ) expr ++ expr --
unary operators ++expr --expr +expr -expr ~ !
creation or cast new (type )expr
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
conditional ? :
= += -= *= /= %= ^= &= |= <<=
assignment >>= >>>=
Branching
• Same as in C:
– if()
– switch()
– conditional expression ? :
The if/else Statements
if (expression) {
statement(s)
}
if (response == OK) {
// code to perform OK action
} else {
// code to perform Cancel action
}
49
The switch Statement
• The syntax of the switch statement is:
switch (expression) {
case value1:
statement-list1
case value2:
statement-list2
case …
}
50
Looping
• Same as in C:
– while()
– for()
– do/while()
– break
– continue
The while Statement
while (expression) {
statement
}
• In addition to while loops, Java has two other
constructs used to perform repetition:
• the do statement
• the for statement
The do Statement
• The do statement has the following syntax:
do statement
statement
while (condition); true
condition
false
53
The for Statement
• The syntax of the for loop is
for (intialization; condition; increment)
statement;
which is equivalent to
initialization;
while (condition) {
statement;
increment;
}
54
Branching Statements
55
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”);
}
}}
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();
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;
}
}
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());
}
}
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
60
Arrays
• An array is an ordered list of values
• Each value has a numeric index
• An array of size N is indexed from zero to
N-1
• The following array of integers has a size of
10 and is indexed from 0 to 9
0 1 2 3 4 5 6 7 8 9
scores 79 87 94 82 67 98 87 81 74 91
61
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
62
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};
63
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
64
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
65
Multidimensional Arrays
66
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;
}}
}}
67
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
68
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.
69
import java.util.*;
class MyVector {
public static void main(String args[]) {
Vector v = new Vector();
String s1;
s1 = new String(“hello ”);
s1 = s1 + s2 + “ davison”;
// + is string concatenation
Comparing Strings
0 9 A Z a z
0 48 57 65 90 97 122
• s1.equals(s2)
– lexicographical comparison
– returns true if s1 and s2 contain the same text
• s1 == s2
– returns true if s1 and s2 refer to the same object
continued
• s1.compareTo(s2)
– returns 0 if s1 and s2 are equal
– returns < 0 if s1 < s2; > 0 if s1 > s2
• s1.startsWith(“text”)
– returns true if s1 starts with “text”
• s1.endsWith(“text”)
– returns true if s1 ends with “text”
Locating Things in Strings
for text analysis
• s1.indexOf(‘c’)
– returns index position of first ‘c’ in s1, otherwise -1
• s1.lastIndexOf(‘c’)
– returns index position of last ‘c’ in s1, otherwise -1
• s1.substring(1, 4)
– returns substring between positions 1 and 3
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
Other String Methods
• The String class is in the java.lang package
– there are many more String methods!
– e.g. s.length()
continued
• 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
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.
class MyPoint {
int x;
int y;
obj.setData(10,20);
obj.display(); // invoking display() method with no parameter
obj.display(30,40); // invoking display() method with two int value
parameters
}
}
Inheritance
class Inheri {
public static void main(String args[]){
Derived obj = new Derived();
continued
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;
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.
Types of Exceptions
• Common exceptions:
– division by zero
– accessing an array outside its bounds
while (i < 4) {
103
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 {
}
104
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
105
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.
JDBC in Use
Java JDBC
program driver
connectivity for Oracle
data processing
utilities driver
for DB2
jdbc-odbc odbc
bridge driver
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
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
JDBC Access Steps
All JDBC programs do the following:
e.g. jdbc:odbc:Books
jdbc:oracle:thin:scott/tiger@193.188.73.12:1521:A8
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();
ResultSet Object
• Stores the results of a SQL query.
Continued
cursor
23 Daher
5 Sirin
17 Emad
98 Odeh
• Cursor operations:
– first(), last(), next(), previous(), etc.
• Typical code:
while( rs.next() ) {
// process the row;
}
simpJDBC.java
// simpJDBC.java
// Displays the firstnames and lastnames
// of the Authors table in the Books db.
import java.sql.*;
// Close down
statement.close();
conn.close();
}
:
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
} // end of main()
• 1. Click on
“32 bit ODBC”
in the Control
Panel.
This displays the
ODBC Data
Sources
Administrator
• 2. Press “Add’ to
add a data source
and select
Microsoft Access
Driver (*.mdb).
Press “Finish”.
• 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”.
• 4. Type in a username
and password (guest).
Click “Ok”
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.
continued
executeUpdate()
• But most SQL statements do not return a table
– DDL statements, e.g. create, drop
– most DML statements, e.g. insert, update
import java.sql.*;
// Close down
statement.close();
conn.close();
}
:
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
} // end of main()
Threads
• Objectives
– describe basic threads in Java
Contents
1. What is Concurrency?
2. Java Threads
3. Scheduling
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 e-mail at the same time
• Most programming languages do not have
concurrent features
– e.g. a program that cannot do several tasks at once
continued
• 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
// Thread creation
Mango m = new Mango();
m.start();
continued
• 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();
2.2. start() and run()
• Threads do not automatically start executing
when created (with new)
– they must be started with start()
import java.io.*;
class threadExs {
public static void main(String[] a)
{
SimpThread t1 = new SimpThread();
t1.start();
continued
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 threadExs2 {
public static void main(String[] a)
{
SleepThread t1 = new SleepThread();
t1.start();
continued
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
continued
• How can threads be made to give turns?
– the yield() function can be called in a thread to force
it to time slice
// an anonymous thread
new Coffee(270).start();
continued
class Coffee extends Thread
{ private int numCups;
public Coffee(int n)
{ numCups = n; }
continued
class Tea extends Thread
{ private int numCups;
public Tea(int n)
{ numCups = n; }
continued
2. I like tea
31. Thread-1 likes coffee
18. Thread-0 likes coffee
1. I like tea tea thread finishes
:
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 first coffee
12. Thread-1 likes coffee
: thread finishes
2. Thread-1 likes coffee
1. Thread-1 likes coffee
$
second coffee
thread finishes
Usage with the yield() calls in
• $ java drinks
300. Thread-0 likes coffee The three threads
270. Thread-1 likes coffee start together
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
: tea thread finishes
continued
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 second coffee
30. Thread-0 likes coffee thread finishes
:
2. Thread-0 likes coffee
1. Thread-0 likes coffee
$ first coffee
thread finishes
Graphics
• Objective
– look at color, fonts, and how to draw
shapes into applet/application windows
Graphics
• Objective
– look at color, fonts, and how to draw
shapes into applet/application windows
Java’s Coordinate System
• Graphical methods use an (X,Y) coordinate
system to place things in a window:
0 +x
0 X axis
(X,Y)
note
+y
Y axis
Coordinate
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
• A graphics object contains methods and
data related to drawing:
– e.g. the drawing area, current font, color
– often called a graphics context
continued
• 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
Graphics Methods: paint()
• public void paint(Graphics g);
– draws the graphics context stored in g which
represents the applet/application window
continued
– 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
repaint()
• 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
continued
• drawXXX() puts an empty outline on the
screen.
• fillXXX() fills the interior with a solid
colour.
java.awt.Component
java.awt.Container
java.awt.Window java.awt.Panel
java.awt.Frame java.applet.Applet
Java Applets
Web browser
Java
interpreter
MyApplet.java
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {
public void paint(Graphics g)
{
……………….;
………………..;
}
}
Simple HTML document
<HTML>
<HEAD>
<TITLE>My First Applet</TITLE>
</HEAD>
<BODY>
<APPLET code=”MyApplet.class”
width=500
height=300>
</APPLET>
</BODY>
</HTML>
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
}
}
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
Applet Life Cycle
•Color.black •Color.lightGray
•Color.blue •Color.magenta
•Color.orange
•Color.cyan
•Color.pink
•Color.darkGray •Color.red
•Color.gray •Color.white
•Color.green •Color.yellow
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);
continued
• Creating a Font object:
public Font(String name, int style, int size);
e.g.
Font f = new Font(“TimesRoman”,
Font.BOLD, 18);
continued
Serif Monospaced
SansSerif
• Five font names can be assumed:
– TimesRoman, Courier, Helvetica, Symbol,
Dialog
(x1,y1)
(x2,y2)
Drawing Lines
import java.applet.*;
import java.awt.*;
public class SimpleLine extends Applet {
public void paint(Graphics g) {
g.drawLine(5,10,20,30);
}
}
(x,y) width
2. Rectangles height
width continued
• public void drawRoundRect(
int x, int y,
int width, int height,
int arcWidth, int arcHeight);
continued
• public void draw3DRect(
int x, int y,
int width, int height,
Boolean raised);
– The rectangle is raised if raised is true;
otherwise lowered.
(x, y)
height
width
continued
• public void drawOval(
int x, int y,
int width, int height);
(x,y) 90
0 degrees
height 180
ending starting angle
angle
width 270
continued
positive sweep
negative sweep
continued
a positive number means “positive
sweep”; negative means “negative
sweep”
continued
• 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
continued
(20,20)
(30,30)
(20,40)
• public void drawPolygon(Polygon p);
– draw the polygon p in the graphics object
– e.g. g.drawPolygon(p);
continued
(20,20)
(30,30)
(20,40)
• e.g.
int xs = {20,30,20};
int ys = {20,30,40};
g.drawPolyline(xs,ys,3);
Examples
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
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.
continued
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/
AWT Controls Overview
We list the AWT controls in two
categories:
– basic controls
– top-level containers
Basic Controls
• Control AWT Class Name
– button Button, CheckBox
– choice Choice
– list List
– menu Menu, MenuBar, MenuItem
– text field TextField
– label Label
– text TextArea
Top-level Containers
• Container AWT Class Name
– frame Frame
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);
}}
Swing GUI components
• In JDK 1.2 and later, GUI interfaces should
be written with the Swing GUI components
continued
• 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
• 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
continued
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)
• Control
– a control is a GUI element
• e.g. a button, textfield, scrollbar
continued
• 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
• 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)
continued
• Graf1.html:
<html>
<applet code="Graf1.class" width="200"
height="100">
</applet>
</html>
Use
• appletviewer Graf1.html
Graf2.java
• import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // for window listener
gf2.addWindowListener(
// anonymous class for window closing
new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit(0); }
}
);
} // end of main()
} // end of paint()
:
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
Use
Fonts.java
• import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
} // end of paint()
:
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
Use
LinesRectsOvals.java
• // Drawing lines, rectangles and ovals
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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()
:
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
Use
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
Basic Controls
• Control Swing Class Name
– button JButton, JCheckBox, JRadioButton
– combo box JComboBox
– list JList
– menu JMenu, JMenuBar, JMenuItem
– slider JSlider
– toolbar JToolbar
– text field JTextField, JPasswordField
Uneditable Displays
• Control Swing Class Name
– label JLabel
– Tooltip JToolTip
– Progress bar JProgressBar
Editable Displays
• Control Swing Class Name
– table JTable
– text JTextPane, JTextArea,
JEditorPane
– tree JColorChooser
– file chooser JFileChooser
Space-saving Containers
• Container Swing Class Name
– scroll pane JScrollPane, JScrollBar
– split pane JSplitPane
– tabbed pane JTabbedPane
Top-level Containers
• Container Swing Class Name
– frame JFrame
– applet JApplet
– dialog JDialog, JOptionPane
Other Containers
• Container Swing Class Name
– panel JPanel
– internal frame JInternalFrame
– layered pane JLayeredPane
– root pane JRootPane
continued
• The layout manager is FlowLayout
– explained later
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Container c = getContentPane();
step 1
c.setLayout( new FlowLayout() );
:
step 2
// JLabel with a string argument step 3
JLabel label1 =
new JLabel( "Label with text" );
label1.setToolTipText( "This is label1" );
c.add( label1 );
step 4
// 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 main()
• 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
• Tooltip text can be added to all GUI controls.
label1.setToolTipText( "This is label1" );
continued
• The frame (window) is created by calling its
constructor inside main()
import javax.swing.*;
import java.awt.*;
// import java.awt.event.*; // not needed
} // end of init()
• There is no main().
continued
• 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
continued
• There is no need for an event handler for
closing the applet and exiting
– that is done automatically
continued
• Event handlers (methods) for different events are
predefined by Java inside listener classes.
continued
Event Handler as a Diagram
class that implements
Program on-screen GUI the listener class
event event handler
method
data
methods
Program Code A typical action is for the
event handler method to
update the data back in the
program.
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
continued
MouseMotionListener
• For efficiency reasons, mouse movement
events are dealt with by a separate listener.
// 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);
}
// the mouse button pressed and the released in one motion
public void mouseClicked(MouseEvent evt) {
mouseX = evt.getX();
mouseY = evt.getY();
repaint();
}
}
• addWindowListener() is the way that the
listener is registered with the frame:
app.addWindowListener(...);
}
Using an Anonymous Class
• A common coding style is to subclass an
adapter class as an anonymous class inside
the program.
continued
• main() in LabelTest.java:
anonymous
class
public static void main( String args[] )
{
LabelTest app = new LabelTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{ System.exit( 0 ); }
}
);
continued
GUI Layout
• Objectives
– describe the basic layout managers for
GUIs
Contents
1. A Reminder on GUI Creation
2. Flow Layout
3. Grid Layout
4. Border Layout
5. Box Layout
6. Combining Layouts
1. Reminder on GUI Creation
Container c = getContentPane();
c.setLayout( new FlowLayout() );
:
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 );
setSize(400,200);
show();
} // end of FlowDemo()
public static void main(String[] args)
{
FlowDemo app = new FlowDemo();
} // end of FlowDemo
Initial Appearance
After Resizing
continued
• 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
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) );
:
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 );
} // end of GridDemo
Appearance
Components
have been
resized to
equally fill
the 400x400
space. Note the
horizontal
and vertical
spacing
between the
components.
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 );
:
Appearance
the 'cancel'
button has
not been
resized
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"
Container c = getContentPane();
// use BorderLayout:
// 10 pixel horiz. gap, 7 pixel vert. gap
c.setLayout( new BorderLayout(10, 7) );
:
// 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" );
} // end of BorderDemo
Appearance
Components
have been Note the
resized to vertical
fill the and
400x400 horizontal
space. spacing
between the
components
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
Container c = getContentPane();
// use BoxLayout: align components vertically
c.setLayout(
new BoxLayout(c, 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");
c.add( jck1 ); c.add( jck2 ); c.add( jck3 );
} // end of BoxDemo
Appearance
With pack()
6. Combining Layouts
• Real GUIs usually require several layout
managers for different parts of the display.
East West
Center
panel p1 panel p2
(vertical box) (vertical box)
image
Container c = getContentPane();
// use default BorderLayout for frame
:
// 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 );
:
// panel 2: vertical box layout
JPanel p2 = new JPanel();
p2.setLayout(
new BoxLayout(p2, BoxLayout.Y_AXIS));
} // end of CombinedDemo
Multimedia
• Objectives
– introduce Java multimedia:
• images, audio, animations
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
Loading Images
URL imageURL =
newURL("http://www.prenhall.com/logo.gif");
java.awt.Image img = this.getImage(imageURL);
– g.drawImage(logo1, 0, 0, this);
• this is the JApplet, an ImageObserver object that draws to
the screen
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
1. Images
• The tasks of LoadImageAndScale.java:
– draw three images in an applet
• an image, full-size and scaled
• an ImageIcon
1.1. Usage
Full-size
Image ImageIcon
Scaled
Image
1.2. LoadImageAndScale.java
• import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
} // end of LoadImageAndScale
LoadImageAndScale.html
• <html>
<applet code="LoadImageAndScale.class"
width=340 height=340>
</applet>
</html>
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
• For example:
play( getDocumentBase(), “hi.au”);
– play “hi.au” after loading it from the same
place as the Web page
2.1. AudioClip Sounds
• A more flexible way of playing sounds is to
use AudioClip methods.
continued
• Methods for playing:
– public void play();
• play the audio clip once
currentSound
ItemStateChanged(...) {... }
anon. class
ActionPerformed(...) {... }
ButtonHandler
LoadAudioAndPlay.java
• // Load an audio clip and play it.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
sound1 = getAudioClip(
getDocumentBase(), "welcome.wav" );
sound2 = getAudioClip(
getDocumentBase(), "hi.au" );
currentSound = sound1;
} // end of init()
// stop sound when user switches Web pages
// (i.e., be polite to the user)
public void stop()
{ currentSound.stop(); }
app
JFrame
paintComponent(...)
{ ... }
actionPerformed(...)
{ repaint();}
timer
LogoAnimator JPanel
3.3. Usage
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
• foo.start(); // start the timer
• foo.stop(); // stop it
• foo.restart(); // restart after a stop
• foo.isRunning(); // boolean test
3.5. LogoAnimator.java
• // Animation a series of images
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
startAnimation();
}
continued
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();
}
continued
public void actionPerformed( ActionEvent e )
{ repaint(); }
if (images[currentImage].getImageLoadStatus()
== MediaTracker.COMPLETE ) {
images[currentImage].paintIcon(
this, g, 0, 0 );
currentImage = (currentImage + 1) %
totalImages;
}
} Check if the image has been loaded.
continued
public Dimension getMinimumSize()
{ return getPreferredSize(); }
continued
public static void main( String args[] )
{
LogoAnimator anim = new LogoAnimator();
app.setSize(
anim.getPreferredSize().width + 10,
anim.getPreferredSize().height + 30 );
app.show();
}
} // end of LogoAnimator
3.6. Notes
• Component Sizes
– JPanel (and other controls and components)
support the methods getMinimumSize() and
getPreferredSize()
continued
• 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 ) {
...}
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/
4.1. JMF 2.1
• Capture, playback, transmit and translate audio,
video and other media
• More details:
– http://java.sun.com/products/
java-media/jmf/index.html
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
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
Input/Output
• Objectives
– discuss stream I/O in Java
Contents
1. Two Common Data Formats
2. Java I/O Essentials
3. Predefined Streams
4. Forms of Input
5. Forms of Output
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
2. Java I/O Essentials
• All I/O in Java is done using streams.
• There are two kinds of streams:
– 8-bit streams, 16-bit streams
• The 8-bit streams are known as:
– InputStreams, OutputStreams
• The 16-bit streams are known as:
– Readers (for input), Writers (for output)
• Class names for I/O almost always contain the
words Reader, Writer, InputStream, or OutputStream
– this helps you identify what they can do
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)
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
Classes for Input
• Data Format Class to use
ASCII / Unicode System.in (keyboard input)
FileReader (file input)
InputStreamReader
(byte stream, e.g. network)
Binary DataInputStream
Object ObjectInputStream
4.1. Reading Chars from the Keyboard
C>
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
• DataInputStream expects binary data
coming from a stream
– to read binary data from a file requires
stream layering with FileInputStream
Binary DataOutputStream
Object ObjectOutputStream
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
continued
• DataInputStream streams can read anything
output by a DataOutputStream
• Layered streams are needed to connect a
DataOutputStream to a binary file.
C>