View
230
Download
0
Category
Preview:
Citation preview
Slide 1 of 107.Lecture J – The Java API Libraries
Lecture J - The Java API Libraries
Unit J1 - Exceptions
Slide 2 of 107.Lecture J – The Java API Libraries
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
Slide 3 of 107.Lecture J – The Java API Libraries
Occurrence of a runtime exceptionpublic 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]); }}
Slide 5 of 107.Lecture J – The Java API Libraries
Runtime exceptions in the Java API
• java.lang.ArithmeticException• java.lang.NullPointerException• java.lang.IllegalArgumentException• java.lang.NegativeArraySizeException• java.lang.ArrayIndexOutOfBoundsException• java.lang.ClassCastException
Slide 6 of 107.Lecture J – The Java API Libraries
Throwing a runtime exceptionpublic 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; }}
Slide 7 of 107.Lecture J – The Java API Libraries
Declaring a new runtime exception
• The RuntimeException class has an empty constructor and one that accepts a string (denoting an error message).
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]; }}
Slide 8 of 107.Lecture J – The Java API Libraries
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
Slide 9 of 107.Lecture J – The Java API Libraries
Catching Exceptionsimport 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);
}
}
}
Slide 10 of 107.Lecture J – The Java API Libraries
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;
}
}
Throwing Checked Exceptions
Slide 11 of 107.Lecture J – The Java API Libraries
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.
Slide 12 of 107.Lecture J – The Java API Libraries
Pumping up an exception
public static void main(String[] args) {
try {
doWithdraws();
} catch (OverDraftException e) {
callManager();
}
}
private static doWithdraws() throws OverDraftException {
// Get list of withdraw orders
for(/* iterate over withdraw orders */)
bankAccount.withdraw(amount)
}
Overdraft!
Hey, no one
Catches this…
I’ll crash the
method!
Slide 13 of 107.Lecture J – The Java API Libraries
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.
Slide 14 of 107.Lecture J – The Java API Libraries
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();
}
Slide 15 of 107.Lecture J – The Java API Libraries
Either catch
// Called when the user chooses to add a gateprivate 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 }}
Slide 16 of 107.Lecture J – The Java API Libraries
or declare
// Called when the user chooses to add a gateprivate userAddsGate() throws UnknownGateException { String type = //... look up gate type Gate gate = makeGate(type); //... adds the gate to the model //...}
Slide 17 of 107.Lecture J – The Java API Libraries
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.
Slide 18 of 107.Lecture J – The Java API Libraries
Throwable class hierarchy
Throwable
ExceptionError
RuntimeException
Slide 19 of 107.Lecture J – The Java API Libraries
Multiple Catchesimport 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); } }}
Slide 20 of 107.Lecture J – The Java API Libraries
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}
Slide 21 of 107.Lecture J – The Java API Libraries
Lecture J - The Java API Libraries
Unit J2 - Streams
Slide 22 of 107.Lecture J – The Java API Libraries
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, ...
Slide 23 of 107.Lecture J – The Java API Libraries
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 ...
Slide 24 of 107.Lecture J – The Java API Libraries
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.
Slide 25 of 107.Lecture J – The Java API Libraries
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.
Slide 26 of 107.Lecture J – The Java API Libraries
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, ...
Slide 28 of 107.Lecture J – The Java API Libraries
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.
Slide 29 of 107.Lecture J – The Java API Libraries
IO Streams
12 72 32 17 83 11 7 91 108
43 55 31 37 34 13 17 1 15
Input stream
Output stream
reading direction
writing direction
Slide 30 of 107.Lecture J – The Java API Libraries
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
Slide 31 of 107.Lecture J – The Java API Libraries
Specific input streams
InputStream
ByteArrayInputStream
FileInputStream PipedInputStream
. . .
Slide 32 of 107.Lecture J – The Java API Libraries
Class InputStream
• Class java.io.InputStream defines several methods that support the abstraction of allowing sequential reading from a stream:
Reads the next byte from the stream. Return -1 if the
end of the stream was reached.
Reads up to b.length bytes from the stream into the
array b. Returns the number of bytes that were read.
public abstract int read() throws IOException
public int read(byte[] b) throws IOException
Slide 33 of 107.Lecture J – The Java API Libraries
Input streams
Reads up to length bytes from the stream into the
array ‘b’ from the index ‘offset’. Returns the number of bytes that were read.
Closes this input stream and releases any system
resources associated with the stream.
• Few additional methods (look up in the API)
public int read(byte[] b, int offset, int length) throws IOException
public void close() throws IOException
Slide 34 of 107.Lecture J – The Java API Libraries
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
Slide 35 of 107.Lecture J – The Java API Libraries
Specific output streams
OutputStream
ByteArrayOutputStream
FileOutputStream PipedOutputStream
. . .
Slide 36 of 107.Lecture J – The Java API Libraries
Class OutputStream
• Class java.io.OutputStream defines several methods that support the abstraction of allowing sequential writing to a stream:
Writes the specified byte (given as an int) to this output stream.
Writes b.length bytes from the specified byte array to
this output stream.
public abstract void write(int b) throws IOException
public void write(byte[] b) throws IOException
Slide 37 of 107.Lecture J – The Java API Libraries
Input streams
Writes length bytes from the specified byte array starting at offset off to this output stream.
Closes this output stream and releases any system
resources associated with the stream.
• Few additional methods (look up in the API)
public void write(byte[] b, int offset, int length) throws IOException
public void close() throws IOException
Slide 38 of 107.Lecture J – The Java API Libraries
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
Slide 39 of 107.Lecture J – The Java API Libraries
Writing to a fileimport 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”); } }}
Slide 40 of 107.Lecture J – The Java API Libraries
Reading from a fileimport 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”); } }}
Slide 41 of 107.Lecture J – The Java API Libraries
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”); } }
Slide 42 of 107.Lecture J – The Java API Libraries
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(); }}
Slide 43 of 107.Lecture J – The Java API Libraries
Lecture J - The Java API Libraries
Unit J3 - Readers and Writers
Slide 44 of 107.Lecture J – The Java API Libraries
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.
Slide 45 of 107.Lecture J – The Java API Libraries
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).
Slide 46 of 107.Lecture J – The Java API Libraries
Writers
Writer writer = new FileWriter(“mail.txt”);
writer.write(‘a’);
writer.write(‘\u0590’); // Hebrew Aleph
Automatic platform
dependent translation
made by the writer
97
97
1424
224
97 224
conversion to
the platform specific
code for aleph
standard ASCII no
conversion needed
Slide 47 of 107.Lecture J – The Java API Libraries
Readers
Reader reader = new FileReader(“mail.txt”);
char c = reader.read(); // c = ‘\u0590’
c = reader.read(); // c = ‘a’
Automatic platform
dependent translation
made by the reader
97
97
1424
224
97 224
conversion from
the platform specific
code for aleph
standard ASCII no
conversion needed
Slide 48 of 107.Lecture J – The Java API Libraries
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
Slide 49 of 107.Lecture J – The Java API Libraries
Specific readers
Reader
CharArrayReader
FileReader PipedReader
. . .
StringReader
Slide 50 of 107.Lecture J – The Java API Libraries
Specific writers
Writer
CharArrayWriter
FileWriter PipedWriter
. . .
StringWriter
Slide 51 of 107.Lecture J – The Java API Libraries
java.io.Reader
Read a single character. Returns the character as an int or -1 if the end of the stream was reached.
Reads up to buffer.length characters into ‘buffer’, returns the number of characters read.
Closes the reader.
• Few additional methods (look up in the API)
public abstract int read() throws IOException
public int read(char[] buffer) throws IOException
public void close() throws IOException
Slide 52 of 107.Lecture J – The Java API Libraries
java.io.Writer
Writes a single character given as an int.
Writes a given char array.
Closes the writer.
• Few additional methods (look up in the API)
public abstract void write(int c) throws IOException
public void write(char[] buffer) throws IOException
public void close() throws IOException
Slide 53 of 107.Lecture J – The Java API Libraries
ToUpperimport 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];
Slide 54 of 107.Lecture J – The Java API Libraries
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.”); } }}
Slide 55 of 107.Lecture J – The Java API Libraries
Lecture J - The Java API Libraries
Unit J4 - Filtered Streams
Slide 56 of 107.Lecture J – The Java API Libraries
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
Slide 57 of 107.Lecture J – The Java API Libraries
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 ); }}
Reading a Short
Slide 58 of 107.Lecture J – The Java API Libraries
Reading a Linepublic 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(); }}
Slide 59 of 107.Lecture J – The Java API Libraries
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
Slide 60 of 107.Lecture J – The Java API Libraries
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.
Slide 61 of 107.Lecture J – The Java API Libraries
Example: BufferedReader
Reader
read()
...
...
BufferedReader
readLine()
BufferedReader
(Reader r)
read()
...
...
Slide 62 of 107.Lecture J – The Java API Libraries
Example: DataInputStream
InputStream
read()
...
...
DataInputStream
readShort()
read()
...
...
Slide 63 of 107.Lecture J – The Java API Libraries
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.”); } }}
Slide 64 of 107.Lecture J – The Java API Libraries
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
Slide 65 of 107.Lecture J – The Java API Libraries
Example: Chaining Decorators
readShort()
read() read() read()
BufferedDataFile
try { DataInputStream input = new DataInputStream( new BufferedInputStream( new FileInputStream(args[0])));} catch (FileNotFoundException fnfe) { // ...}
Slide 66 of 107.Lecture J – The Java API Libraries
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);}
Slide 68 of 107.Lecture J – The Java API Libraries
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
Slide 69 of 107.Lecture J – The Java API Libraries
Some AWT components
Button
TextField
Label
Scrollbar
Choice
Frame
others ....
Slide 70 of 107.Lecture J – The Java API Libraries
Class component
Component
TextComponentButton
All components are derived from the class java.awt.Component
TextFieldTextArea
...
Slide 71 of 107.Lecture J – The Java API Libraries
Class Component
• Class component defines the properties common to all components: location, size, background color, foreground color, visibility, ...
public Dimension getSize()public void setSize(Dimension d)public void setSize(int x, int y)public Point getLocation()public void setLocation(Point p)public void setLocation(int x, int y)public Color getBackground()public void setBackground(Color c)...
Slide 72 of 107.Lecture J – The Java API Libraries
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 void add(Component c)public void remove(Component c) public Component[] getComponents()public int getComponentCount()public void setLayout(LayoutManager manager)...
Slide 73 of 107.Lecture J – The Java API Libraries
Opening a Yellow Frameimport java.awt.*; // A sample program that opens a yellow frameclass FrameExample {
public static void main(String[] args) { Frame frame = new Frame(“Example”); frame.setSize(400,300); frame.setBackground(Color.yellow); frame.setVisible(true); }}
Slide 74 of 107.Lecture J – The Java API Libraries
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); }}
Slide 75 of 107.Lecture J – The Java API Libraries
SampleFrameimport 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); }}
Slide 76 of 107.Lecture J – The Java API Libraries
Adding componentsimport java.awt.*;//A sample program that opens a frame with a button // on itpublic 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); }}
Slide 78 of 107.Lecture J – The Java API Libraries
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.. )
Slide 79 of 107.Lecture J – The Java API Libraries
Layout Managers
Frame
FlowLayout
add(new Button(“Ok”))
layoutContainer(this)
Slide 80 of 107.Lecture J – The Java API Libraries
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
Slide 81 of 107.Lecture J – The Java API Libraries
FlowLayout
setLayout(new FlowLayout());add(new Label(“Name:”));add(new TextField(10));add(new Button(“Ok”));
Slide 82 of 107.Lecture J – The Java API Libraries
GridLayout
setLayout(new GridLayout(2,2));add(new Button(“A”));add(new Button(“B”));add(new Button(“C”));add(new Button(“D”));
Slide 83 of 107.Lecture J – The Java API Libraries
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);
Slide 84 of 107.Lecture J – The Java API Libraries
Combination of layouts
Panel with
GridLayout
Frame with
BorderLayout
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]));}
Slide 85 of 107.Lecture J – The Java API Libraries
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
Slide 86 of 107.Lecture J – The Java API Libraries
Graphicsimport java.awt.*;
// A frame that displays some graphics on itpublic 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); } }}
Slide 88 of 107.Lecture J – The Java API Libraries
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().
Slide 89 of 107.Lecture J – The Java API Libraries
LEDFigureimport 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(); }}
Slide 90 of 107.Lecture J – The Java API Libraries
Graphics
setOn()
LED
Windowing
Systemupdate()
paint()
repaint()
Please
update my
display
clear display
paint
display
Graphics
Slide 91 of 107.Lecture J – The Java API Libraries
Lecture J - The Java API Libraries
Unit J6 - Events
Slide 92 of 107.Lecture J – The Java API Libraries
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
Slide 93 of 107.Lecture J – The Java API Libraries
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.
Slide 94 of 107.Lecture J – The Java API Libraries
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
Slide 95 of 107.Lecture J – The Java API Libraries
ClickingFrameimport 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); }}
Slide 96 of 107.Lecture J – The Java API Libraries
Mouse events and listenerspublic interface MouseListener { void mousePressed (MouseEvent event); void mouseReleased (MouseEvent event); void mouseClicked (MouseEvent event); void mouseEntered (MouseEvent event); void mouseExited (MouseEvent event);}
public class MouseEvent { int getX(){ … } int getY(){ … } Point getPoint{ … } …}
Slide 97 of 107.Lecture J – The Java API Libraries
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 void mousePressed (MouseEvent event){} public void mouseReleased (MouseEvent event){} public void mouseEntered (MouseEvent event){} public void mouseExited (MouseEvent event){}}
LocationMouseListener
Slide 98 of 107.Lecture J – The Java API Libraries
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); }}
DotsApplet
Slide 99 of 107.Lecture J – The Java API Libraries
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
Slide 100 of 107.Lecture J – The Java API Libraries
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) { }}
Slide 101 of 107.Lecture J – The Java API Libraries
LocationMouseListenerimport 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()); }}
Slide 102 of 107.Lecture J – The Java API Libraries
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
Slide 103 of 107.Lecture J – The Java API Libraries
DotsApplet with an inner classimport 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()); }
Slide 104 of 107.Lecture J – The Java API Libraries
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 } }}
Slide 105 of 107.Lecture J – The Java API Libraries
DotsApplet with an anonymous classimport 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(); }
Slide 106 of 107.Lecture J – The Java API Libraries
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); }}
Recommended