Lecture J The Java API Libraries - PowerPoint PPT Presentation

About This Presentation
Title:

Lecture J The Java API Libraries

Description:

The method may try to catch and handle the exceptional situation ... After all catches in a try-catch block, a finally clause may appear. ... – PowerPoint PPT presentation

Number of Views:52
Avg rating:3.0/5.0
Slides: 108
Provided by: noamn
Category:
Tags: api | java | lecture | libraries | try

less

Transcript and Presenter's Notes

Title: Lecture J The Java API Libraries


1
Lecture J - The Java API Libraries
  • Unit J1 - Exceptions

2
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

3
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 lt a.length j)
System.out.println(aj)
4
Program Crash due to a runtime exception
5
Runtime exceptions in the Java API
  • java.lang.ArithmeticException
  • java.lang.NullPointerException
  • java.lang.IllegalArgumentException
  • java.lang.NegativeArraySizeException
  • java.lang.ArrayIndexOutOfBoundsException
  • java.lang.ClassCastException

6
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 lt1 hgt12 m lt0 mgt59 slt0
sgt59) throw new IllegalArgumentException(
) hours h minutes m
seconds s
7
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).

8
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

9
Catching Exceptions
import java.io. public class FirstLine
public static void main(String args)
String name args0 try
BufferedReader file new
BufferedReader(new FileReader(name))
String line file.readLine()
System.out.println(line) catch
(IOException e) System.out.println(Proble
m e)
10
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 gt balance) throw new
OverDraftException() balance - amount
11
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.

12
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
Ill crash the method!
13
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 _at_exception
    tag.

14
Documenting Exceptions
/ Creates a Gate of a given type _at_param
type The type of the required gate _at_return A
Gate of the required type _at_exception
UnknownGateException If type doesnt 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()
15
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,
dont add the gate
16
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 //...
17
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.

18
Throwable class hierarchy
Throwable
Error
Exception
RuntimeException
19
Multiple Catches
import java.io. public class FirstLine
public static void main(String args)
String name args0 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)

20
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
21
Lecture J - The Java API Libraries
  • Unit J2 - Streams

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

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

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

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

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

27
Scenario
Application
28
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.

29
IO Streams
12 72 32 17 83
11 7 91 108
Input stream
reading direction
43 55 31 37 34
13 17 1 15
Output stream
writing direction
30
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

31
Specific input streams
InputStream
. . .
FileInputStream
PipedInputStream
ByteArrayInputStream
32
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
33
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.
  • Closes this input stream and releases any
    system
  • resources associated with the stream.
  • Few additional methods (look up in the API)

public void close() throws IOException
34
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

35
Specific output streams
OutputStream
. . .
FileOutputStream
PipedOutputStream
ByteArrayOutputStream
36
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
37
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
38
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

39
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
i0 iltNUMBER_OF_TOSSES i) int
randomThrow (int)(Math.random()6)1
output.write(randomThrow)
output.close() catch (IOException ioe)
System.err.println(Couldnt write to
file)
40
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(Couldnt read
from file)
41
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 lturlgt ltfilenamegt public class Download
public static void main(String args)
try download(args0, args1)
catch (ArrayIndexOutOfBoundsException aioobe)
System.err.println(Wrong
usage.) catch (IOException ioe)
System.err.println(Download failed)
42
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 outputnew FileOutputStream(file
name) int b while ((binput.read())!-1
) output.write(b)
output.close()
43
Lecture J - The Java API Libraries
  • Unit J3 - Readers and Writers

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

45
Java Unicode
  • One of the important aspects of Java is its
    platform independence
  • Therefore Java uses Unicode
  • However, most environments dont 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).

46
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
conversion to the platform specific code for aleph
97
224
standard ASCII no conversion needed
97 224
47
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
conversion from the platform specific code for
aleph
97
224
standard ASCII no conversion needed
97 224
48
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

49
Specific readers
Reader
. . .
FileReader
PipedReader
CharArrayReader
StringReader
50
Specific writers
Writer
. . .
FileWriter
PipedWriter
CharArrayWriter
StringWriter
51
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
52
java.io.Writer
public abstract void write(int c) throws
IOException
  • 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 void write(char buffer) throws
IOException
public void close() throws IOException
53
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 ltsourcegt lttargetgt class
ToUpper public static void main(String
args) if (args.length!2)
System.err.println(Invalid usage.)
return String sourceName args0
String targetName args1
54
ToUpper (cont.)
try Reader reader new
FileReader(sourceName) Writer writer new
FileWriter(targetName) int c
while ((creader.read())!-1) c
Character.toUpperCase((char)c)
writer.write(c) write.close()
//very important !!! catch (IOException
ioe) System.err.println(Copying
failed.)
55
Lecture J - The Java API Libraries
  • Unit J4 - Filtered Streams

56
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

57
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 ltlt 8 low )
58
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()
59
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 dont need all combinations at once

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

61
Example BufferedReader
BufferedReader
BufferedReader (Reader r)
readLine()
Reader
read()
read() ... ...
...
...
62
Example DataInputStream
DataInputStream
readShort() read() ... ...
InputStream
read() ... ...
63
Printing a text file
public class type public static void
main(String args) try
BufferedReader reader new
BufferedReader(new FileReader(args0))
String line while ((linereader.readLine())
!null) System.out.println(line)
catch (IOException ioe)
System.err.println(Reading failed.)

64
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

65
Example Chaining Decorators
try DataInputStream input new
DataInputStream( new BufferedInputStream(
new FileInputStream(args0))) catch
(FileNotFoundException fnfe) // ...

read()
read()
read()
Buffered
Data
File
readShort()
66
InputStreamReader
  • InputStreamReader bridges InputStream and Reader
    classes

URL url new URL(...) BufferedReader reader
new BufferedReader( new InputStreamReader(u
rl.openStream())) String line while ((line
reader.readLine())!null)
System.out.println(line)
67
Lecture J - The Java API Libraries
  • Unit J5 - GUI

68
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

69
Some AWT components
Frame
Button
TextField
Label
Scrollbar
Choice
others ....
70
Class component
  • All components are derived from the class
    java.awt.Component

Component
Button
TextComponent
...
TextField
TextArea
71
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) ...
72
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() pub
lic void setLayout(LayoutManager manager) ...
73
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(Co
lor.yellow) frame.setVisible(true)
74
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)

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

76
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)
77
ButtonFrame screenshot
78
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.. )

79
Layout Managers
add(new Button(Ok))
Frame
layoutContainer(this)
FlowLayout
80
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

81
FlowLayout
setLayout(new FlowLayout()) add(new
Label(Name)) add(new TextField(10)) add(new
Button(Ok))
82
GridLayout
setLayout(new GridLayout(2,2)) add(new
Button(A)) add(new Button(B)) add(new
Button(C)) add(new Button(D))
83
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)
84
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.se
tLayout(new GridLayout(4,4)) String labels
7,8,9,,4,5, ... for (int i0
iltlabels.length i) buttonsPanel.add(new
Button(labelsi))
85
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 dont 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

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

87
Graphics
88
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().

89
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,getSiz
e().width-1,getSize().height-1) public
void setOn(boolean state) isOn state
repaint()
90
Graphics
LED
  • Please
  • update my
  • display

setOn()
repaint()
Windowing System
  • clear display

update()
  • paint
  • display

paint()
Graphics
91
Lecture J - The Java API Libraries
  • Unit J6 - Events

92
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

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

94
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 buttons
    addActionListner(ActionListner) method

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

96
Mouse events and listeners
public 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
97
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 void mousePressed (MouseEvent event)
public void mouseReleased (MouseEvent event)
public void mouseEntered (MouseEvent event)
public void mouseExited (MouseEvent event)

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

99
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

100
MouseAdapter
package java.awt.event public abstract class
MouseAdapter implements
MouseListener public void mousePressed(MouseEv
ent e) public void mouseReleased(MouseEv
ent e) public void mouseEntered(MouseEven
t e) public void mouseExited(MouseEvent
e) public void mouseClicked(MouseEvent
e)
101
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())

102
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 classs fields they are in the inner
    classs 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

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

104
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)
xevent.getX() //direct access to x
yevent.getY()// direct access to x

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

106
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)
xevent.getX() yevent.getY()
) public void paint(Graphics g)
g.setColor(Color.green) g.fillOval(x -
r/2 , y - r/2, r, r)
107
Lecture J - The Java API Libraries
Write a Comment
User Comments (0)
About PowerShow.com