Download OOP Course 9

Document related concepts
no text concepts found
Transcript
OBJECT ORIENTED
PROGRAMMING
Course 9
Loredana STANCIU
[email protected]
Room B613
APPLETS
A program written in the Java programming
language that can be included in an HTML
page
 A special kind of Java program that a
browser enabled with Java technology can
download from the internet and run
 Embedded inside a web page and runs in the
context of a browser
 Extends the java.applet.Applet class

DEFINING AN APPLET





import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
 public void paint (Graphics g){
 g.drawString("Hello World", 20, 20);
 }
}
METHODS FOR MILESTONES

Milestones are major events in an applet's
life cycle
 init
method:
 useful
for one-time initialization that doesn't take very
long
 contains the code that you would normally put into a
constructor
 Keep the method short so that your applet can load
quickly
METHODS FOR MILESTONES
 start
method:
 starts
the execution of an applet
 every applet that performs tasks after initialization
must override this method
 It is good practice to return quickly from the start
method
 stop
method:
 should
suspend the applet's execution, so that it
doesn't take up system resources when the user isn't
viewing the applet's page
 most applets that override the start should also
override the stop method
METHODS FOR MILESTONES
 destroy
method:
 available
for applets that need to release additional
resources
 many applets don't need to override the destroy
method
 keep implementations of the destroy method as short
as possible
EXAMPLE










import java.applet.Applet;
import java.awt.Graphics;
public class Simple extends Applet {
StringBuffer buffer;
public void init() {
buffer = new StringBuffer();
addItem("initializing... ");}
public void start() {
addItem("starting... ");}
………………………………………………………………………………………………………………………
EXAMPLE










………………………………………………………………………………………………………………………
public void stop() {
addItem("stopping... ");}
public void destroy() {
addItem("preparing for unloading...");}
private void addItem(String newWord) {
System.out.println(newWord);
buffer.append(newWord);
repaint();}
………………………………………………………………………………………………………………………
EXAMPLE





………………………………………………………………………………………………………………………
public void paint(Graphics g) {
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);
g.drawString(buffer.toString(), 5, 15);

}


}
LIFE CYCLE OF AN APPLET

An applet can react to major events in the following
ways:





It can initialize itself.
It can start running.
It can stop running.
It can perform a final cleanup, in preparation for being
unloaded.
Loading an applet:

An instance of the applet's controlling class (an Applet
subclass) is created.
The applet initializes itself.

The applet starts running.

LIFE CYCLE OF AN APPLET

Leaving and Returning to the Applet's Page:



Reloading an applet:


When leaving the page, the browser stops and destroys
the applet.
When returning to the page, the browser initializes and
starts a new instance of the applet.
The current instance of the applet is stopped and
destroyed and a new instance is created.
Quitting the browser:

The applet has the opportunity to stop itself and perform
a final cleanup before the browser exits.
LIFE CYCLE OF AN APPLET




init(): intended for whatever initialization is
needed for the applet
start(): automatically called after init() and
whenever user returns to the page containing the
applet after visiting other pages
stop(): automatically called whenever the user
moves away from the page containing applets or to
stop an animation
destroy(): called when the browser shuts down
normally.
APPLET’S EXECUTION ENVIRONMENT

An applet runs in the context of a browser
 The
Java Plug-in software controls the launch
and execution of applets
 JavaScript interpreter runs the JavaScript code
on a web page

Java Plug-in:
 creates
a worker thread for every applet
 launches an applet in an instance of the Java
Runtime Environment (JRE) software
APPLET’S EXECUTION ENVIRONMENT
LOADING APPLETS IN A WEB PAGE
<applet code=AppletWorld.class
width="200" height="200">
 </applet>

appletviewer AppletWorld.html
 when making changes to the applet's code
while it is loaded in the browser, then
recompile the applet and press the "Shift +
Reload" button in the browser to load the
new version

CONVERTING APPLICATIONS TO APPLETS
An application: a standalone program
consisting of at least one class with a main
method.
 Applets

 do
not have a main method
 several
methods are called at different points in
the execution of an applet

The difference between Java applets and
applications lies in how they are run
CONVERTING APPLICATIONS TO APPLETS

Create a subclass of
java.applet.Applet and override the
init method to initialize the applet's
resources the same way the main method
initializes the application's resources.

init might be called more than once and should
be designed accordingly. The top-level Panel
needs to be added to the applet in init; usually it
was added to a Frame in main.
USING THE PAINT METHOD

Used to draw the applet's representation within a
browser page

public void paint(Graphics g) {
 /*Draw a Rectangle around the applet's
display area.*/
 g.drawRect(0, 0, getWidth() - 1,
getHeight() - 1);
 /*Draw the current string inside the
rectangle.*/
 g.drawString(buffer.toString(), 5, 15);
}

The Graphic class
Is the abstract base class for all graphics
contexts that allow an application to draw
onto components that are realized on various
devices
 A Graphics object encapsulates state
information needed for the basic rendering
operations that Java supports

The Graphic class

This state information includes the following
properties:

The Component object on which to draw.

A translation origin for rendering and clipping
coordinates.
The current clip.
The current color.
The current font.
The current logical pixel operation function (XOR or
Paint).
The current XOR alternation color





The Graphic class

All coordinates that appear as arguments to
the methods of a Graphics object are
considered relative to the translation origin of
this Graphics object prior to the invocation
of the method.
The Graphic class

public void translate(int x, int y)
 Translates

the origin of the graphics context to
the point (x, y) in the current coordinate system
public Color getColor()
 Gets

this graphics context's current color.
public void setColor(Color c)
 Sets
this graphics context's current color to the
specified color. All subsequent graphics
operations using this graphics context use this
specified color.
The Graphic class

public Font getFont()
 Gets

the current font.
public void setFont(Font font)
 Sets

this graphics context's font to the specified
font. All subsequent text operations using this
graphics context use this font.
public void drawLine(int x1, int y1,
int x2, int y2)
 Draws
a line, using the current color, between the
points (x1, y1) and (x2, y2) in this graphics
context's coordinate system.
The Graphic class

public void drawRect(int x, int y,
int width, int height)
 Draws

the outline of the specified rectangle. The
rectangle is drawn using the graphics context's
current color.
public void clearRect(int x, int y,
int width, int height)
 Clears
the specified rectangle by filling it with the
background color of the current drawing surface.
This operation does not use the current paint
mode.
The Graphic class

public abstract void drawOval(int x,
int y, int width, int height)
 Draws

the outline of an oval. The result is a circle
or ellipse that fits within the rectangle specified
by the x, y, width, and height arguments.
public abstract void drawArc(int x,
int y, int width, int height,
int startAngle, int arcAngle)
 Draws
the outline of a circular or elliptical arc
covering the specified rectangle. Angles are
interpreted such that 0 degrees is at the 3 o'clock
position
The Graphic class

public void drawString(String str,
int x, int y)


Draws the text given by the specified string, using this
graphics context's current font and color. The baseline of
the leftmost character is at position (x, y) in this graphics
context's coordinate system.
public abstract void drawPolygon
(int[] xPoints, int[] yPoints,
int nPoints)
 Draws
a closed polygon defined by arrays of x
and y coordinates. Each pair of (x, y) coordinates
defines a point.
The Color class


Used encapsulate colors in the default sRGB color
space
Predefined values for colors:
 BLACK, BLUE, CYAN, DARK GREY, GREY,
GREEN, LIGHT GREY, MAGENTA, ORANGE,
PINK, RED, WHITE, YELLOW,
The Applet class
Must be the superclass of any applet that is
to be embedded in a Web page or viewed by
the Java Applet Viewer
 Provides a standard interface between
applets and their environment.
 More on

http://java.sun.com/j2se/1.4.2/docs/api/java/appl
et/Applet.html
The Applet tag






<APPLET
 CODEBASE = codebaseURL
 ARCHIVE = archiveList
 CODE = appletFile ...or... OBJECT = serializedApplet
 ALT = alternateText
 NAME = appletInstanceName
 WIDTH = pixels
 HEIGHT = pixels
 ALIGN = alignment
 VSPACE = pixels HSPACE = pixels >
<PARAM NAME = appletAttribute1 VALUE = value>
<PARAM NAME = appletAttribute2 VALUE = value>
...
alternateHTML
</APPLET>
The Applet tag

CODEBASE = codebaseURL


OPTIONAL attribute specifies the base URL of the applet
— the directory that contains the applet's code. If this
attribute is not specified, then the document's URL is
used.
ARCHIVE = archiveList

OPTIONAL attribute describes one or more archives
containing classes and other resources that will be
"preloaded". The classes are loaded using an instance of
an AppletClassLoader with the given CODEBASE.
The Applet tag

CODE = appletFile


REQUIRED attribute gives the name of the file that
contains the applet's compiled Applet subclass. This file
is relative to the base URL of the applet. The value
appletFile can be of the form classname.class or of the
form packagename.classname.class.
ALT = alternateText

OPTIONAL attribute specifies any text that should be
displayed if the browser understands the APPLET tag but
can't run Java applets.
The Applet tag

NAME = appletInstanceName


OPTIONAL attribute specifies a name for the applet
instance, which makes it possible for applets on the
same page to find (and communicate with) each other.
WIDTH = pixels HEIGHT = pixels

REQUIRED attributes give the initial width and height (in
pixels) of the applet display area, not counting any
windows or dialogs that the applet brings up.
The Applet tag

ALIGN = alignment


VSPACE = pixels HSPACE = pixels


OPTIONAL attribute specifies the alignment of the applet.
The possible values of this attribute are: left, right, top,
texttop, middle, absmiddle, baseline, bottom, absbottom.
OPTIONAL attributes specify the number of pixels above
and below the applet (VSPACE) and on each side of the
applet (HSPACE).
<PARAM NAME = appletAttribute1 VALUE =
value>

The only way to specify an applet-specific attribute.
Applets access their attributes with the
getParameter() method.
Example — Drawing lines



import java.applet.*;
import java.awt.*;
public class DrawingLines extends Applet {
 int width, height;
 public void init() {
 width = getSize().width;
 height = getSize().height;
 setBackground( Color.black ); }
 public void paint( Graphics g ) {
 g.setColor( Color.green );
 for ( int i = 0; i < 10; ++i ) {
 g.drawLine( width, height, i * width /
10, 0 ); } } }
Example — Drawing lines

<applet width=300 height=300
code="DrawingLines.class"> </applet>
Example — Drawing Other Stuff



import java.applet.*;
import java.awt.*;
public class DrawingLines extends Applet {
 int width, height;
 public void init() {
 width = getSize().width;
 height = getSize().height;
 setBackground( Color.black ); }
 public void paint( Graphics g ) {
 g.setColor( Color.red );
 g.drawRect( 10, 20, 100, 15 );
 g.setColor( Color.pink );
 g.fillRect( 240, 160, 40, 110 );
…
Example — Drawing Other Stuff
…
 g.setColor(
Color.blue );
 g.drawOval( 50, 225, 100, 50 );
 g.setColor( Color.orange );
 g.fillOval( 225, 37, 50, 25 );
 g.setColor(
Color.yellow );
 g.drawArc( 10, 110, 80, 80, 90, 180 );
 g.setColor( Color.cyan );
 g.fillArc( 140, 40, 120, 120, 90, 45 );
…
Example — Drawing Other Stuff
…
 g.setColor(
Color.magenta );
 g.fillArc( 150, 150, 100, 100, 90, 90 );
 g.setColor( Color.black );
 g.fillArc( 160, 160, 80, 80, 90, 90 );
 g.setColor(
Color.green );
 g.drawString( "Groovy!", 50, 150 );


}
}
Example — Drawing Other Stuff

The output:
Example — Mouse Input






import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Mouse3 extends Applet implements
MouseListener, MouseMotionListener {
 int width, height;
 int mx, my;
 public void init() {
 width = getSize().width; height =
getSize().height; setBackground( Color.black );
 mx = width/2; my = height/2;
 addMouseListener(this);
 addMouseMotionListener( this ); }
…
Example — Mouse Input


………
 public void mouseEntered( MouseEvent e ) {
 // the pointer enters the applet's
rectangular area }
 public void mouseExited( MouseEvent e ) {
 // the pointer leaves the applet's
rectangular area }
 public void mouseClicked( MouseEvent e ) {
 // a press and release of a mouse button
with no motion in between}
………
Example — Mouse Input

………
 public
void mousePressed( MouseEvent e ){
 // called after a button is pressed down
 isButtonPressed = true;
 setBackground( Color.gray );
 repaint();
 e.consume(); }
 public void mouseReleased( MouseEvent e ) {
 // a button is released
 isButtonPressed = false;
 setBackground( Color.black );
 repaint();
 e.consume(); }

………
Example — Mouse Input


………
 public void mouseMoved( MouseEvent e ) {
 // during motion when no buttons are
 mx = e.getX(); my = e.getY();
 showStatus( "Mouse at (" + mx + "," +
")" );
 repaint(); e.consume(); }
 public void mouseDragged( MouseEvent e )
 // during motion with buttons down
 mx = e.getX(); my = e.getY();
 showStatus( "Mouse at (" + mx + "," +
")" );
 repaint(); e.consume(); }
………
down
my +
{
my +
Example — Mouse Input


………
 public void paint( Graphics g ) {
 if ( isButtonPressed ) {
 g.setColor( Color.black ); }
 else { g.setColor( Color.gray ); }
 g.fillRect( mx-20, my-20, 40, 40 ); }
}
Example — Keyboard Input




import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Keyboard1 extends Applet implements
KeyListener, MouseListener {
 int width, height; int x, y; String s = "";
 public void init() {
 width = getSize().width; height =
getSize().height;
 setBackground( Color.black );
 x = width/2; y = height/2;
 addKeyListener( this );
 addMouseListener( this );
 }
 …
Example — Keyboard Input









…
public void keyPressed( KeyEvent e ) { }
public void keyReleased( KeyEvent e ) { }
public void keyTyped( KeyEvent e ) {
 char c = e.getKeyChar();
 if ( c != KeyEvent.CHAR_UNDEFINED ) {
 s = s + c;
 repaint();
 e.consume(); } }
public void mouseEntered( MouseEvent e ) { }
public void mouseExited( MouseEvent e ) { }
public void mousePressed( MouseEvent e ) { }
public void mouseReleased( MouseEvent e ) { }
…
Example — Keyboard Input




}
…
public void mouseClicked( MouseEvent e ) {
 x = e.getX(); y = e.getY();
 s = "";
 repaint();
 e.consume(); }
public void paint( Graphics g ) {
 g.setColor( Color.gray );
 g.drawLine( x, y, x, y-10 );
 g.drawLine( x, y, x+10, y );
 g.setColor( Color.green );
 g.drawString( s, x, y ); }
Example — Threads





import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
public class Clock extends Applet implements Runnable
{
 int width, height;
 Thread t = null;
 boolean threadSuspended;
 int hours=0, minutes=0, seconds=0;
 String timeString = "";
 public void init() {
 width = getSize().width; height =
getSize().height;
 setBackground( Color.black ); }
Example — Threads


…
public void start() {
 if ( t == null ) {
 t = new Thread( this );
 t.setPriority( Thread.MIN_PRIORITY );
 threadSuspended = false;
 t.start(); }
 else {
 if ( threadSuspended ) {
 threadSuspended = false;
 synchronized( this ) { notify(); }
 } } }
 public void stop() { threadSuspended = true; }
…
Example — Threads


…
public void run() {
 try {
 while (true) {
 Calendar cal = Calendar.getInstance();
 hours = cal.get( Calendar.HOUR_OF_DAY );
 if ( hours > 12 ) hours -= 12;
 minutes = cal.get( Calendar.MINUTE );
 seconds = cal.get( Calendar.SECOND );
 SimpleDateFormat formatter = new
SimpleDateFormat( "hh:mm:ss",
Locale.getDefault() );
 Date date = cal.getTime();
 timeString = formatter.format( date );
 …
Example — Threads

…

if ( threadSuspended ) {
 synchronized( this ) {
 while ( threadSuspended ) { wait(); }
 } }
 repaint();
 t.sleep( 1000 );} }
 catch (InterruptedException e) { } }
void drawHand( double angle, int radius, Graphics
g ) {
 angle -= 0.5 * Math.PI;
 int x = (int)( radius*Math.cos(angle) );
 int y = (int)( radius*Math.sin(angle) );
 g.drawLine( width/2, height/2, width/2 + x,
height/2 + y ); }
…


Example — Threads



…
void drawWedge( double angle, int radius, Graphics g ) {
 angle -= 0.5 * Math.PI;
 int x = (int)( radius*Math.cos(angle) );
 int y = (int)( radius*Math.sin(angle) );
 angle += 2*Math.PI/3;
 int x2 = (int)( 5*Math.cos(angle) );
 int y2 = (int)( 5*Math.sin(angle) );
 angle += 2*Math.PI/3;
 int x3 = (int)( 5*Math.cos(angle) );
 int y3 = (int)( 5*Math.sin(angle) );
 g.drawLine( width/2+x2, height/2+y2, width/2 + x,
height/2 + y );
 g.drawLine( width/2+x3, height/2+y3, width/2 + x,
height/2 + y );
 g.drawLine( width/2+x2, height/2+y2, width/2 + x3,
height/2 + y3 ); }
…
Example — Threads



}
…
public void paint( Graphics g ) {
 g.setColor( Color.gray );
 drawWedge( 2*Math.PI * hours / 12, width/5, g );
 drawWedge( 2*Math.PI * minutes / 60, width/3, g );
 drawHand( 2*Math.PI * seconds / 60, width/2, g );
 g.setColor( Color.white );
 g.drawString( timeString, 10, height-10 ); }
REFERENCES


http://java.sun.com/docs/books/tutorial/deployme
nt/applet/index.html
http://www.dgp.toronto.edu/~mjmcguff/learn/java/