Insert Lesson Name
Download
Report
Transcript Insert Lesson Name
Lecture J - The Java API Libraries
Unit J1 - Exceptions
Lecture J – The Java API Libraries
Slide 1 of 107.
Exceptions in Java
• Java uses the notion of exception for 3 related (but
different) purposes:
Errors: an internal Java implementation error was discovered
• E.g: out of memory
Runtime exceptions: a programming logic error was discovered
• E.g. division by 0
Checked Exceptions: an exceptional case was discovered
• E.g. file not found
• Errors and Runtime exceptions will usually cause the
program to crash
• Checked exceptions should usually be handled by the
programmer
Lecture J – The Java API Libraries
Slide 2 of 107.
Occurrence of a runtime exception
public class ExceptionExample {
public static void main(String[] args) {
int[] a = {2, 4, 6, 8};
for(int j = 0; j <= a.length ; j++)
System.out.println(a[j]);
}
}
Lecture J – The Java API Libraries
Slide 3 of 107.
Program Crash due to a runtime exception
Lecture J – The Java API Libraries
Slide 4 of 107.
Runtime exceptions in the Java API
• java.lang.ArithmeticException
• java.lang.NullPointerException
• java.lang.IllegalArgumentException
• java.lang.NegativeArraySizeException
• java.lang.ArrayIndexOutOfBoundsException
• java.lang.ClassCastException
Lecture J – The Java API Libraries
Slide 5 of 107.
Throwing a runtime exception
public class Clock {
private int hours, minutes, seconds;
// constructors and methods
public void setTime(int h, int m, int s){
if (h <1 || h>12 || m <0 || m>59 || s<0 || s>59)
throw new IllegalArgumentException();
hours = h;
minutes = m;
seconds = s;
}
}
Lecture J – The Java API Libraries
Slide 6 of 107.
Declaring a new runtime exception
public class StackUnderflowException
extends RuntimeException {}
public class Stack {
int elements[];
int top;//next empty location in the elements array
// … constructor, push(), isEmpty()
public int pop() {
if (isEmpty())
throw new StackUnderflowException();
return elements[--top];
}
}
•
The RuntimeException class has an empty constructor and one that
accepts a string (denoting an error message).
Lecture J – The Java API Libraries
Slide 7 of 107.
Checked Exceptions
• Checked Exceptions denote exceptional situations that
need to be dealt with.
• They are dealt with by “catching” them
Using the try { … } catch { … } statement
• Their possible occurrence in a method is considered part
of the interface of the method
Must be declared using the throws keyword
• Checked exceptions in the Java API:
java.net.ConnectException
java.io.IOException
java.io.EOFException
java.io.FileNotFoundException
java.util.TooManyListenersException
Lecture J – The Java API Libraries
Slide 8 of 107.
Catching Exceptions
import java.io.*;
public class FirstLine {
public static void main(String[] args){
String name = args[0];
try {
BufferedReader file =
new BufferedReader(new FileReader(name));
String line = file.readLine();
System.out.println(line);
} catch (IOException e) {
System.out.println(“Problem: ” + e);
}
}
}
Lecture J – The Java API Libraries
Slide 9 of 107.
Throwing Checked Exceptions
public class OverDraftException extends Exception { }
public class BankAccount {
private float balance;
// constructors, fields, and methods
public void withdraw(float amount)
throws OverDraftException {
if (amount > balance)
throw new OverDraftException();
balance -= amount;
}
}
Lecture J – The Java API Libraries
Slide 10 of 107.
Exception life-cycle
• When a program performs an illegal operation the
following happens:
The regular flow of the program stops
An exception object is created, which encapsulates the information
about the problem that occurred
The method may try to catch and handle the exceptional situation
If the method ignores the exception the method execution ceases.
An exception then appears at the place in which the method was
called
If the exception is not handled anywhere, the program crashes.
Lecture J – The Java API Libraries
Slide 11 of 107.
Pumping up an exception
public static void main(String[] args) {
try {
doWithdraws();
} catch (OverDraftException e) {
callManager();
}
}
Overdraft!
private static doWithdraws() throws OverDraftException {
// Get list of withdraw orders
Hey, no one
Catches this…
for(/* iterate over withdraw orders */)
bankAccount.withdraw(amount)
I’ll crash the
}
method!
Lecture J – The Java API Libraries
Slide 12 of 107.
Declaring for exceptions
• If a method must declare all the non run-time exceptions it
may throw.
• The declaration is done using the throws keyword
• The user of the method is warned against possible
exceptions that this method can throw
• The exceptions that might be thrown by a method should
also be documented with the @exception tag.
Lecture J – The Java API Libraries
Slide 13 of 107.
Documenting Exceptions
/**
* Creates a Gate of a given type
* @param type The type of the required gate
* @return A Gate of the required type
* @exception UnknownGateException If ‘type’ doesn’t
* refer to a familiar gate.
*/
public Gate makeGate(String type) throws UnkownGateException {
if (type.equals(“OR”))
return new OrGate();
if (type.equals(“AND”))
return new AndGate();
if (type.equals(“NOT”))
return new NotGate();
throw new UnknownGateException();
}
Lecture J – The Java API Libraries
Slide 14 of 107.
Either catch
// Called when the user chooses to add a gate
private userAddsGate() {
String type = //... look up the selected gate type
try {
Gate gate = makeGate(type);
//... adds the gate to the model
//...
} catch (UnknownGateException uge) {
// ignore this, don’t add the gate
}
}
Lecture J – The Java API Libraries
Slide 15 of 107.
or declare
// Called when the user chooses to add a gate
private userAddsGate() throws UnknownGateException {
String type =
//... look up gate type
Gate gate = makeGate(type);
//... adds the gate to the model
//...
}
Lecture J – The Java API Libraries
Slide 16 of 107.
Exceptions Hierarchy
• All the classes for indicating run-time errors are derived
from the class java.lang.Throwable.
• The object you deliver to the throw statement must be an
instance of class Throwable
• The constructor of class Throwable initializes all the
information about the location where the exception
occurred, the state of the run-time stack etc. In this way
this information is set for every exception object.
• The following diagram explains the inheritance hierarchy
for exceptions.
Lecture J – The Java API Libraries
Slide 17 of 107.
Throwable class hierarchy
Throwable
Error
Exception
RuntimeException
Lecture J – The Java API Libraries
Slide 18 of 107.
Multiple Catches
import java.io.*;
public class FirstLine {
public static void main(String[] args){
String name = args[0];
try {
BufferedReader file =
new BufferedReader(new FileReader(name));
String line = file.readLine();
System.out.println(line);
} catch (FileNotFoundException e) {
System.out.println(“File not found: “ + name);
} catch (IOException e) {
System.out.println(“Problem: ” + e);
}
}
}
Lecture J – The Java API Libraries
Slide 19 of 107.
finally
• After all catches in a try-catch block, a finally clause may
appear.
• The finally section of code is executed before exiting from
the try-block, whether or not an exception occurred.
• The finally section is executed even if the try-catch block
was exited by a return or break statement.
try {
// acquire resources
// do stuff
} catch (E1 e) { …
} catch (E2 e) { …
} finally {
// release resources
}
Lecture J – The Java API Libraries
Slide 20 of 107.
Lecture J - The Java API Libraries
Unit J2 - Streams
Lecture J – The Java API Libraries
Slide 21 of 107.
Input / Output
• A program often needs to communicate with other
devices. In other words it should receive input and send
output.
• There are many types of input sources:
Reading a file from a local disk / diskette
Receiving a web page from a remote server
Receiving a communication message through a network.
Receiving a signal from a sensor of a robot
Scanner, video camera, ...
Mouse, keyboard, joystick, ...
Lecture J – The Java API Libraries
Slide 22 of 107.
Input / Output
• Similarly, there are many types of output destinations:
Writing to a file on a local disk / diskette
Sending query information to a remote web server
Sending communication message to a remote host. Sending a
command to a robot controller.
Printing a document to a printer / fax
Displaying graphics on the screen
...
Lecture J – The Java API Libraries
Slide 23 of 107.
GUI inputs and outputs
• GUI related inputs and outputs are usually treated
separately. They are given special API about which we will
learn later.
• GUI inputs and outputs include receiving mouse,
keyboard and similar events, and displaying graphics on
the screen.
Lecture J – The Java API Libraries
Slide 24 of 107.
IO API - design goal
• We want to make a distinction between the content of the
data an application receives/sends and the
source/destination of the data
• The same kind of data can be stored on different types of
media.
• Similarly a given media can store different types of data.
Lecture J – The Java API Libraries
Slide 25 of 107.
Scenario
• Suppose we have an image processing application. It can
read images, manipulate them and store them on a
permanent storage.
• We want our application to be able to read images from
different types of sources:
local image files, remote images from the web, receiving an image
from a scanner, ...
• We want to be able to output the image to various types of
destinations:
save the image to a local file, print the image on a printer, send the
image to a fax recipient, ...
Lecture J – The Java API Libraries
Slide 26 of 107.
Scenario
Application
Lecture J – The Java API Libraries
Slide 27 of 107.
IO Streams
• We can achieve the separation by designing a common
interface for reading any kind of data, and common
interface for writing any kind of data.
• This interface is implemented by the notion of input and
output streams.
• Any input can be represented as a sequence of bits. For
convenience we divide the sequence into a sequence of
bytes.
• Similarly any output can be represented as a growing
sequence of bytes.
Lecture J – The Java API Libraries
Slide 28 of 107.
IO Streams
12
72
32
17
83
11
7
91
108
Input stream
reading direction
43
55
writing direction
31
37
34
13
17
1
15
Output stream
Lecture J – The Java API Libraries
Slide 29 of 107.
Input streams
• An input stream is a sequence of bytes that is attached to
•
•
•
•
some input source.
You can read data from the stream in a sequential order.
One byte at a time or several bytes at a time.
Input streams are represented by the abstract class
java.io.InputStream.
Subclasses of InputStream defines input streams that are
related to various data sources
Class InputStream gives a common interface for receiving
data from various types of data sources
Lecture J – The Java API Libraries
Slide 30 of 107.
Specific input streams
InputStream
...
FileInputStream
PipedInputStream
ByteArrayInputStream
Lecture J – The Java API Libraries
Slide 31 of 107.
Class InputStream
• Class java.io.InputStream defines several methods that
support the abstraction of allowing sequential reading from a
stream:
public abstract int read() throws IOException
Reads the next byte from the stream. Return -1 if the
end of the stream was reached.
public int read(byte[] b) throws IOException
Reads up to b.length bytes from the stream into the
array b. Returns the number of bytes that were read.
Lecture J – The Java API Libraries
Slide 32 of 107.
Input streams
public int read(byte[] b, int offset, int length)
throws IOException
Reads up to length bytes from the stream into the
array ‘b’ from the index ‘offset’. Returns the number of
bytes that were read.
public void close() throws IOException
Closes this input stream and releases any system
resources associated with the stream.
• Few additional methods (look up in the API)
Lecture J – The Java API Libraries
Slide 33 of 107.
Output streams
• An output stream is attached to an output destination to
•
•
•
•
which you can write data.
You can write data to the stream in a sequential order.
One byte at a time or several bytes at a time.
Output streams are represented by the abstract class
java.io.OutputStream.
Subclasses of OutputStream defines output streams
that are related to various data destinations
Class OutputStream gives a common interface for
sending data to various types of data destinations
Lecture J – The Java API Libraries
Slide 34 of 107.
Specific output streams
OutputStream
...
FileOutputStream
PipedOutputStream
ByteArrayOutputStream
Lecture J – The Java API Libraries
Slide 35 of 107.
Class OutputStream
• Class java.io.OutputStream defines several methods that
support the abstraction of allowing sequential writing to a
stream:
public abstract void write(int b)
throws IOException
Writes the specified byte (given as an int) to this output
stream.
public void write(byte[] b) throws IOException
Writes b.length bytes from the specified byte array to
this output stream.
Lecture J – The Java API Libraries
Slide 36 of 107.
Input streams
public void write(byte[] b, int offset,
int length) throws IOException
Writes length bytes from the specified byte array starting
at offset off to this output stream.
public void close() throws IOException
Closes this output stream and releases any system
resources associated with the stream.
• Few additional methods (look up in the API)
Lecture J – The Java API Libraries
Slide 37 of 107.
Reading/Writing from/to files
• java.io.FileInputStream is a subclass of InputStream that
let you read a file (viewed as a sequence of bytes)
• java.io.FileOutputStream is a subclass of OutputStream
that let you write data to a file (as a sequence of bytes)
• Both classes have constructors that get the path of the file
as a parameter
Lecture J – The Java API Libraries
Slide 38 of 107.
Writing to a file
import java.io.*;
class GenerateDiceData {
static final int NUMBER_OF_TOSSES = 100000;
public static void main(String[] args) {
try {
OutputStream output = new FileOutputStream(“dice.dat”);
for (long i=0; i<NUMBER_OF_TOSSES; i++) {
int randomThrow = (int)(Math.random()*6)+1;
output.write(randomThrow);
}
output.close();
} catch (IOException ioe) {
System.err.println(“Couldn’t write to file”);
}
}
}
Lecture J – The Java API Libraries
Slide 39 of 107.
Reading from a file
import java.io.*;
public class Count6Occurrences {
static final int LOOK_FOR = 6;
public static void main(String[] args) {
long count = 0;
try {
InputStream input = new FileInputStream(“dice.dat”);
int result;
while ((result = input.read()) != -1)
if (result == LOOK_FOR)
count++;
input.close();
System.out.println(count + “ occurrences”);
} catch (IOException ioe) {
System.err.println(“Couldn’t read from file”);
}
}}
Lecture J – The Java API Libraries
Slide 40 of 107.
Downloading a file from the web page
import java.io.*;
import java.net.URL;
// This program downloads a file from a given url
// and saves it to the local file
// Usage: java Download <url> <filename>
public class Download {
public static void main(String[] args) {
try {
download(args[0], args[1]);
} catch (ArrayIndexOutOfBoundsException aioobe) {
System.err.println(“Wrong usage.”);
} catch (IOException ioe) {
System.err.println(“Download failed”);
}
}
Lecture J – The Java API Libraries
Slide 41 of 107.
Downloading a file from the web (cont.)
// Downloads a remote file to the local disk.
// source - The url of the remote file
// filename - The name of the target file.
private static void download(String source,
String filename) throws IOException {
InputStream input =(new URL(source)).openStream();
OutputStream output=new FileOutputStream(filename);
int b;
while ((b=input.read())!=-1) {
output.write(b);
}
output.close();
}
}
Lecture J – The Java API Libraries
Slide 42 of 107.
Lecture J - The Java API Libraries
Unit J3 - Readers and Writers
Lecture J – The Java API Libraries
Slide 43 of 107.
Textual vs. binary data
• We often make a distinction between textual data and
other kind of data
• We refer to files that stores text as ‘text files’ and to
other files as ‘binary files’.
• Binary files stores their information in various formats.
In order to understand the content of a binary file you
need to have a viewer that knows how to read the
format the file is written with.
• The structure of text files is more simple. It uses an
encoding that gives a numeric code for each symbol
and the text is stored as a list of numbers.
Lecture J – The Java API Libraries
Slide 44 of 107.
Java & Unicode
• One of the important aspects of Java is its platform
•
•
•
•
independence
Therefore Java uses Unicode
However, most environments don’t support Unicode yet
but only use ASCII.
Unicode uses two bytes per character while ASCII uses
one byte
Java IO library overcomes this problem using Readers
and Writers that translate between internal Unicode
representation and external ASCII representation (with
local extensions).
Lecture J – The Java API Libraries
Slide 45 of 107.
Writers
Writer writer = new FileWriter(“mail.txt”);
writer.write(‘a’);
writer.write(‘\u0590’); // Hebrew Aleph
97
1424
Automatic platform
dependent translation
made by the writer
standard ASCII no
conversion needed
97
97
224
224
conversion to
the platform specific
code for aleph
Lecture J – The Java API Libraries
Slide 46 of 107.
Readers
Reader reader = new FileReader(“mail.txt”);
char c = reader.read(); // c = ‘\u0590’
c = reader.read();
// c = ‘a’
97
1424
Automatic platform
dependent translation
made by the reader
standard ASCII no
conversion needed
97
97
224
224
conversion from
the platform specific
code for aleph
Lecture J – The Java API Libraries
Slide 47 of 107.
Readers & Writers
• java.io.Reader is an abstract class that defines a common
•
•
•
•
interface for reading textual data
It is the counterpart of InputStream
You can read from a reader characters in a sequential
manner. One character at a time, or several characters at
a time.
Similarly, java.io.Writer is an abstract class that defines a
common interface for reading textual data.
It is the counterpart of OutputStream
Lecture J – The Java API Libraries
Slide 48 of 107.
Specific readers
Reader
...
FileReader
CharArrayReader
PipedReader
StringReader
Lecture J – The Java API Libraries
Slide 49 of 107.
Specific writers
Writer
...
FileWriter
CharArrayWriter
PipedWriter
StringWriter
Lecture J – The Java API Libraries
Slide 50 of 107.
java.io.Reader
public abstract int read() throws IOException
Read a single character. Returns the character as an int
or -1 if the end of the stream was reached.
public int read(char[] buffer) throws IOException
Reads up to buffer.length characters into ‘buffer’, returns
the number of characters read.
public void close() throws IOException
Closes the reader.
• Few additional methods (look up in the API)
Lecture J – The Java API Libraries
Slide 51 of 107.
java.io.Writer
public abstract void write(int c) throws IOException
Writes a single character given as an int.
public void write(char[] buffer) throws IOException
Writes a given char array.
public void close() throws IOException
Closes the writer.
• Few additional methods (look up in the API)
Lecture J – The Java API Libraries
Slide 52 of 107.
ToUpper
import java.io.*;
// This class reads a text file and writes it into
// another text file after converting all letters to
// uppercase.
// Usage: java ToUpper <source> <target>
class ToUpper {
public static void main(String[] args) {
if (args.length!=2) {
System.err.println(“Invalid usage.”);
return;
}
String sourceName = args[0];
String targetName = args[1];
Lecture J – The Java API Libraries
Slide 53 of 107.
ToUpper (cont.)
try {
Reader reader = new FileReader(sourceName);
Writer writer = new FileWriter(targetName);
int c;
while ((c=reader.read())!=-1) {
c = Character.toUpperCase((char)c);
writer.write(c);
}
write.close(); //very important !!!
} catch (IOException ioe) {
System.err.println(“Copying failed.”);
}
}
}
Lecture J – The Java API Libraries
Slide 54 of 107.
Lecture J - The Java API Libraries
Unit J4 - Filtered Streams
Lecture J – The Java API Libraries
Slide 55 of 107.
Reading “non-primitive” data
• The data we want to read/write usually has more complex
structure: primitive data types other than char or short,
lines, or even more complex: tables, images,
compressed/encrypted data...
• Basic solution: Extend existing input or output streams
Provide methods for handling the non-primitive data
Lecture J – The Java API Libraries
Slide 56 of 107.
Reading a Short
public class ShortInputStream extends
SomeInputStream{
// ...
public short readShort() throws EOFException {
int hi,low;
if ((hi = this.read()) == -1)
throw new EOFException();
if ((low = this.read()) == -1)
throw new EOFException();
return (short)(hi << 8 | low );
}
}
Lecture J – The Java API Libraries
Slide 57 of 107.
Reading a Line
public class LineReader extends SomeReader {
// ...
public String readLine() throws EOFException {
StringBuffer line = new StringBuffer();int c;
while ((c = this.read())!=-1) {
if (c!=‘\n’)
line.append((char)c);
else
return line.toString();
}
if (line.equals(“”))
throw new EOFException();
}
}
Lecture J – The Java API Libraries
Slide 58 of 107.
Design Problem
• There are many enhancements for reading/writing data
Reading complex types of data (lines, objects, ints)
Buffering
“pushing back” something that was already read
• There are many types of input/output streams
• If we would include all enhancements in all types of
streams we will end up with a lot of duplicated code and it
would be hard to add new enhancements or new types of
streams.
• We usually don’t need all combinations at once
Lecture J – The Java API Libraries
Slide 59 of 107.
Solution - Decorator Pattern
• Use a “decorator”: a class that is derived from
•
•
•
•
•
Reader, and has another Reader object as a member
(received by the constructor of the new class).
All Reader methods are “forwarded” to the inner
Reader object.
New attributes (methods) use the inner Reader object
as well.
We gain two things: The “old” interface is preserved,
and we can “chain” several functionalities.
Same solution concept for Writer, InputStream and
OutputStream.
In Java, “decorators” are called “Filters”, and the
base class for adding attributes is FilterXXX.
Lecture J – The Java API Libraries
Slide 60 of 107.
Example: BufferedReader
BufferedReader
BufferedReader
(Reader r)
readLine()
read()
...
...
Reader
read()
...
...
Lecture J – The Java API Libraries
Slide 61 of 107.
Example: DataInputStream
DataInputStream
readShort()
read()
...
...
InputStream
read()
...
...
Lecture J – The Java API Libraries
Slide 62 of 107.
Printing a text file
public class type {
public static void main(String[] args) {
try {
BufferedReader reader =
new BufferedReader(new FileReader(args[0]));
String line;
while ((line=reader.readLine())!=null)
System.out.println(line);
} catch (IOException ioe) {
System.err.println(“Reading failed.”);
}
}
}
Lecture J – The Java API Libraries
Slide 63 of 107.
Filters in java.io.*
• DataInputStream & DataOutputStream
Read and write all primitive Java data types
• ObjectInputStream & ObjectOutputStream
•
Read and write full objects
Objects must be “Serializable”
BufferedReader/Writer/InputStream/OutputStream
Provide buffering
BufferedReader/Writer allow also reading complete lines
• LineNumberReader & LineNumberInputStream
Allow access to input line numbers
Lecture J – The Java API Libraries
Slide 64 of 107.
Example: Chaining Decorators
try {
DataInputStream input = new DataInputStream(
new BufferedInputStream(
new FileInputStream(args[0])));
} catch (FileNotFoundException fnfe) {
// ...
}
read()
Data
read()
Buffered
read()
File
readShort()
Lecture J – The Java API Libraries
Slide 65 of 107.
InputStreamReader
• InputStreamReader bridges InputStream and Reader
classes:
URL url = new URL(“...“);
BufferedReader reader =
new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine())!=null) {
System.out.println(line);
}
Lecture J – The Java API Libraries
Slide 66 of 107.
Lecture J - The Java API Libraries
Unit J5 - GUI
Lecture J – The Java API Libraries
Slide 67 of 107.
AWT & Swing
• Java has two packages for GUI: Swing and AWT
• Originally Java came with the AWT (Abstract Window
•
•
•
•
•
Toolkit)
AWT was very basic. Developers wanted more.
Swing is a much richer.
AWT is still intended to be used in restricted environments
(such as PDAs)
We will learn AWT since it is much simpler
Swing is not very different conceptually
Lecture J – The Java API Libraries
Slide 68 of 107.
Some AWT components
Button
Frame
TextField
Label
Scrollbar
Choice
others ....
Lecture J – The Java API Libraries
Slide 69 of 107.
Class component
All
components are derived from the class java.awt.Component
Component
Button
TextComponent
TextArea
...
TextField
Lecture J – The Java API Libraries
Slide 70 of 107.
Class Component
• Class component defines the properties common to all
components: location, size, background color, foreground
color, visibility, ...
public
public
public
public
public
public
public
public
...
Dimension getSize()
void setSize(Dimension d)
void setSize(int x, int y)
Point getLocation()
void setLocation(Point p)
void setLocation(int x, int y)
Color getBackground()
void setBackground(Color c)
Lecture J – The Java API Libraries
Slide 71 of 107.
Container
• Container is a subclass of Component that is a superclass
for all Components that can contain other components.
• It adds to Component the functionality of adding/removing
components
public
public
public
public
public
...
void add(Component c)
void remove(Component c)
Component[] getComponents()
int getComponentCount()
void setLayout(LayoutManager manager)
Lecture J – The Java API Libraries
Slide 72 of 107.
Opening a Yellow Frame
import java.awt.*;
// A sample program that opens a yellow frame
class FrameExample {
public static void main(String[] args) {
Frame frame = new Frame(“Example”);
frame.setSize(400,300);
frame.setBackground(Color.yellow);
frame.setVisible(true);
}
}
Lecture J – The Java API Libraries
Slide 73 of 107.
Sub-classing Frame
• A better code would be to define a new type of Frame
with the required properties. In this way the code is more
encapsulated.
import java.awt.*;
// A sample program that opens a yellow frame
public class FrameExample {
public static void main(String[] args) {
new SampleFrame().setVisible(true);
}
}
class SampleFrame extends Frame {
public SampleFrame() {
super(“Example”);
setSize(400,300);
setBackground(Color.yellow);
}
}
Lecture J – The Java API Libraries
Slide 74 of 107.
SampleFrame
import java.awt.*;
// A sample program that opens a yellow frame
class SampleFrame extends Frame{
public static void main(String[] args) {
new SampleFrame().setVisible(true);
}
public SampleFrame() {
super(“Example”);
setSize(400,300);
setBackground(Color.yellow);
}
}
Lecture J – The Java API Libraries
Slide 75 of 107.
Adding components
import java.awt.*;
//A sample program that opens a frame with a button
// on it
public class ButtonFrame extends Frame{
public ButtonFrame() {
setSize(400,300);
Button okButton = new Button(“OK”);
add(okButton);
}
public static void main(String[] args) {
new ButtonFrame().setVisible(true);
}
}
Lecture J – The Java API Libraries
Slide 76 of 107.
ButtonFrame screenshot
Lecture J – The Java API Libraries
Slide 77 of 107.
Layout Managers
• Were are the components are added?
• There are two ways to layout components on a container:
Set the exact size and location of every component
Use a LayoutManager
• Every container has its own LayoutManager object
• The LayoutManager is responsible for the the layout of
the component inside the container
• The LayoutManager is consulted whenever there is a
need to rearrange the components inside the container
(container size changed, component added.. )
Lecture J – The Java API Libraries
Slide 78 of 107.
Layout Managers
add(new Button(“Ok”))
Frame
layoutContainer(this)
FlowLayout
Lecture J – The Java API Libraries
Slide 79 of 107.
Layout Managers
• There a various types of Layout Managers. Each has
its strategy for arranging the components.
• Layout managers given with java.awt:
FlowLayout, BorderLayout, GridLayout, CardLayout,
GridBagLayout
• You can define your own layout managers by
implementing the interface java.awt.LayoutManager
• LayoutManager is an example of the Strategy pattern
Lecture J – The Java API Libraries
Slide 80 of 107.
FlowLayout
setLayout(new FlowLayout());
add(new Label(“Name:”));
add(new TextField(10));
add(new Button(“Ok”));
Lecture J – The Java API Libraries
Slide 81 of 107.
GridLayout
setLayout(new GridLayout(2,2));
add(new Button(“A”));
add(new Button(“B”));
add(new Button(“C”));
add(new Button(“D”));
Lecture J – The Java API Libraries
Slide 82 of 107.
GridLayout
setLayout(new BorderLaout());
add(new Button(“North”), BorderLayout.NORTH);
add(new Button(“East”), BorderLayout.EAST);
add(new Button(“South”), BorderLayout.SOUTH);
add(new Button(“West”), BorderLayout.WEST);
add(new Button(“Center”), BorderLayout.CENTER);
Lecture J – The Java API Libraries
Slide 83 of 107.
Combination of layouts
Frame with
BorderLayout
Panel with
GridLayout
setLayout(new BorderLaout());
TextField display = new TextField();
add(display, BorderLayout.NORTH);
Panel buttonsPanel = new Panel();
buttonsPanel.setLayout(new GridLayout(4,4));
String[] labels = {“7”,”8”,”9”,”+”,”4”,”5”, ... };
for (int i=0; i<labels.length; i++) {
buttonsPanel.add(new Button(labels[i]));
}
Lecture J – The Java API Libraries
Slide 84 of 107.
paint() method
• Every component can serve as a graphical context
• In order to draw on a component, you override its paint
method to define the drawing.
• You don’t call the paint method, it is called automatically
by the windowing system whenever there is a need to
display the component
• paint receives as parameter a Graphics object which has
methods for drawing on the component
Lecture J – The Java API Libraries
Slide 85 of 107.
Graphics
import java.awt.*;
// A frame that displays some graphics on it
public class GraphicsExample extends Frame {
public void paint(Graphics painter) {
painter.setColor(Color.black);
painter.drawLine(20,20,400,300);
painter.setColor(Color.blue);
painter.drawRect(50,50,150,100);
painter.setColor(Color.yellow);
painter.fillOval(250,100,80,80);
painter.setColor(Color.green);
painter.fillRect(100,200,150,100);
}
}
}
Lecture J – The Java API Libraries
Slide 86 of 107.
Graphics
Lecture J – The Java API Libraries
Slide 87 of 107.
Graphics
• In order to display a drawing that is not fixed, the
•
•
•
•
•
implementation of paint() should depend on the state of
the object
You have to always be ready to paint everything from
scratch when paint() is called.
Thus your state will need to always contain all the
information about the “contents” of the painting
Whenever the state changes, we need to call the repaint()
method in order to refresh the display of the component.
repaint() asks the windowing system to call the paint()
method with the suitable graphics object.
Actually, the windowing system calls the method update()
which clear the display and then call the method paint().
Lecture J – The Java API Libraries
Slide 88 of 107.
LEDFigure
import java.awt.*;
public class LEDFigure extends Component {
private boolean isOn;
public void paint(Graphics g) {
g.setColor(isOn ?
Color.red.brighter() : Color.red.darker());
g.fillOval(0,0,getSize().width-1,getSize().height-1);
g.setColor(Color.black);
g.drawOval(0,0,getSize().width-1,getSize().height-1);
}
public void setOn(boolean state) {
isOn = state;
repaint();
}
}
Lecture J – The Java API Libraries
Slide 89 of 107.
Graphics
LED
setOn()
Please
update my
display
repaint()
clear
display
update()
paint
display
paint()
Windowing
System
Graphics
Lecture J – The Java API Libraries
Slide 90 of 107.
Lecture J - The Java API Libraries
Unit J6 - Events
Lecture J – The Java API Libraries
Slide 91 of 107.
Events
• The whole point of having a GUI Button is so the user can
•
•
•
•
•
•
push it and make something in the program happen.
How can the program be notified when the user pushes a
button?
When you create the Button, you tell it which object to
notify when the user pushes it
When the user pushes the button, the class Button calls
back to the object that needs to be notified
The Button sends an Event to the observing object
This is an example of the observer-observable pattern
Components in Java usually follow this pattern
Lecture J – The Java API Libraries
Slide 92 of 107.
AWT event handling
• All components of the AWT fire events when the user
•
•
•
•
•
does something interesting with them.
Objects handle events fired by AWT components by
registering as listeners to the events they fire.
Each type of event is a class
Each type of listener is an interface
The various events fired by AWT components and the
interfaces of the corresponding listeners are defined in
package java.awt.event
You can find out which events are supported by a
component by searching its API for addXXXListener() and
removeXXXListener() pairs.
Lecture J – The Java API Libraries
Slide 93 of 107.
ActionEvents
• When a Button is pushed by the user is fires an
ActionEvent
• An ActionListner listens to ActionEvents
• Its actionPerformed(ActionEvent) method is
called
• An ActionListener registers to receive
ActionEvents by calling the button’s
addActionListner(ActionListner) method
Lecture J – The Java API Libraries
Slide 94 of 107.
ClickingFrame
import java.awt.*; import java.awt.event.*;
class ClickedListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println(“clicked”);
}
}
public class ClickingFrame extends Frame {
public ClickingFrame() {
Button okButton = new Button(“OK”);
add(okButton);
pack();
ActionListener listener = new ClickedListener();
okButton.addActionListener(listener);
}
public static void main(String[] args) {
new ClickingFrame().setVisible(true);
}
}
Lecture J – The Java API Libraries
Slide 95 of 107.
Mouse events and listeners
public
void
void
void
void
void
}
interface MouseListener {
mousePressed (MouseEvent event);
mouseReleased (MouseEvent event);
mouseClicked (MouseEvent event);
mouseEntered (MouseEvent event);
mouseExited (MouseEvent event);
public class MouseEvent {
int getX(){ … }
int getY(){ … }
Point getPoint{ … }
…
}
Lecture J – The Java API Libraries
Slide 96 of 107.
LocationMouseListener
import java.applet.Applet; import java.awt.*;
import java.awt.event.*;
public class LocationMouseListener implements MouseListener {
private DotsApplet owner;
public LocationMouseListener(DotsApplet owner) {
this.owner = owner;
}
public void mouseClicked (MouseEvent event){
owner.setXY(event.getX(), event.getY());
}
public
public
public
public
void
void
void
void
mousePressed (MouseEvent event){}
mouseReleased (MouseEvent event){}
mouseEntered (MouseEvent event){}
mouseExited (MouseEvent event){}
}
Lecture J – The Java API Libraries
Slide 97 of 107.
DotsApplet
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DotsApplet extends Applet {
private int x, y;
private static final r = 10;
public void setXY(int x, int y) {
this.x = x ;
this.y = y ;
repaint();
}
public void init() {
x = 50;
y = 50;
addMouseListener(new LocationMouseListener(this));
}
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillOval(x - r/2 , y - r/2, r, r);
}
}
Lecture J – The Java API Libraries
Slide 98 of 107.
Adapters
• In the previous example the Listener class needed to
implement all the methods defined in the Listener
interface even though it was interested only in
implementing one of them.
• To avoid this, the API include for every listener interface
that defines more than a single method, an adapter class
that implements the interface in a trivial way.
• Now you just have to subclass the adapter, and override
only the required methods
Lecture J – The Java API Libraries
Slide 99 of 107.
MouseAdapter
package java.awt.event;
public abstract class MouseAdapter
implements MouseListener{
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
}
Lecture J – The Java API Libraries
Slide 100 of 107.
LocationMouseListener
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class LocationMouseListener extends MouseAdapter {
private DotsApplet owner;
public LocationMouseListener(DotsApplet owner) {
this.owner = owner;
}
public void mouseClicked (MouseEvent event){
owner.setXY(event.getX(), event.getY());
}
}
Lecture J – The Java API Libraries
Slide 101 of 107.
Inner Classes and Anonymous classes
• A Class may contain inner classes inside it
• Each object of the inner class type lives in the context of
•
•
•
•
an object of the outer class.
The inner class objects have direct access to the outer
class’s fields – they are in the inner class’s scope.
The main use of inner classes is to have listeners that
have direct access to a class
In many such cases the class is used once
Such classes may be defined without a name –
anonymous classes
Lecture J – The Java API Libraries
Slide 102 of 107.
DotsApplet with an inner class
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DotsApplet implement Applet {
private int x, y;
private static final r = 10;
public void setXY(int x, int y) {
this.x = x ;
this.y = y ;
repaint();
}
public void init() {
x = 50;
y = 50;
//note that there is no “this” argument
addMouseListener(new LocationMouseListener());
}
Lecture J – The Java API Libraries
Slide 103 of 107.
DotsApplet with an inner class (cont.)
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillOval(x - r/2 , y - r/2, r, r);
}
class LocationMouseListener extends MouseAdapter {
//no owner field
public void mouseClicked (MouseEvent event){
x=event.getX(); //direct access to x
y=event.getY();// direct access to x
}
}
}
Lecture J – The Java API Libraries
Slide 104 of 107.
DotsApplet with an anonymous class
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DotsApplet implement Applet {
private int x, y;
private static final r = 10;
public void setXY(int x, int y) {
this.x = x ;
this.y = y ;
repaint();
}
Lecture J – The Java API Libraries
Slide 105 of 107.
DotsApplet with an anonymous class (cont.)
public void init() {
x = 50;
y = 50;
//note the use of the anonymous MouseAdapter
addMouseListener(new MouseAdapter(){
public void mouseClicked (MouseEvent event){
x=event.getX();
y=event.getY();
}
} );
}
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillOval(x - r/2 , y - r/2, r, r);
}
}
Lecture J – The Java API Libraries
Slide 106 of 107.
Lecture J - The Java API Libraries
Lecture J – The Java API Libraries
Slide 107 of 107.