Title: Java Applets
1Java Applets
- A small application that runs with a Web browser
- Can be tested with the Java utility appletviewer.
- The applet is run from an HTML file
2Source Java Code for an Applet
import java.applet. import java.awt. public
class Myapplet extends Applet public void
paint (Graphics mygraph)
mygraph.drawString (I am working in Java)
mygraph.drawRect(50, 50, 100, 30)
3HTML file for the Applet
ltHTMLgt ltBODYgt ltAPPLET CODE Myapplet.class
WIDTH310 HEIGHT 200gt lt/APPLETgt lt/BODYgt lt/HTMLgt
4Applets with GUIs
- Access the applet class
- Access the awt package -- The Abstract Windowing
Toolkit - import java.applet.
- import java.awt.
- These applets will normally need to declare and
create GUI objects from the awt package
5Placement of GUI Objects
- After creating the GUI objects, they are placed
on the viewer window - The default placing is left-to-right and
top-to-bottom (the FlowLayout layout manager)
6GreetingApplet
- This applet uses
- Two Label objects (prompt and greeting)
- One TextField object (inputLine)
- After declaring these objects, they need to be
created, then they need to be associated with the
applet by invoking the add method to make the
objects visible.
7Applet Constructor
public GreetingApplet () prompt new Label
(Type your name ) greeting new Label()
inputLine new TextField (20) // now make
these objects visible add(prompt)
add(greeting) add(inputLine)
8Applets
- A Java application is a stand-alone program with
a main method (like the ones we've seen so far) - An applet is a Java program that is intended to
transported over the web and executed using a web
browser - An applet can also be executed using the
appletviewer tool of the Java Software
Development Kit - An applet doesn't have a main method
- Instead, there are several special methods that
serve specific purposes - The paint method, for instance, is automatically
executed and is used to draw the applets contents
9Applets
- The paint method accepts a parameter that is an
object of the Graphics class - A Graphics object defines a graphics context on
which we can draw shapes and text - The Graphics class has several methods for
drawing shapes - The class that defines the applet extends the
Applet class - This makes use of inheritance, an object-oriented
concept.
10Applets
- An applet is embedded into an HTML file using a
tag that references the bytecode file of the
applet class - It is actually the bytecode version of the
program that is transported across the web - The applet is executed by a Java interpreter that
is part of the browser
11Drawing Shapes
- Let's explore some of the methods of the Graphics
class that draw shapes in more detail - A shape can be filled or unfilled, depending on
which method is invoked - The method parameters specify coordinates and
sizes - Recall from Chapter 1 that the Java coordinate
system has the origin in the upper left corner - Many shapes with curves, like an oval, are drawn
by specifying its bounding rectangle - An arc can be thought of as a section of an oval
12Drawing a Line
10
150
20
45
13Drawing a Rectangle
50
20
page.drawRect (50, 20, 100, 40)
14Drawing an Oval
175
20
bounding rectangle
page.drawOval (175, 20, 50, 80)
15The Color Class
- A color is defined in a Java program using an
object created from the Color class - The Color class also contains several static
predefined colors - Every graphics context has a current foreground
color - Every drawing surface has a background color
16A Simple Applet --- Digital Clock
- import java.awt.
- import java.util.Calendar
- public class DigitalColok
- extends java.applet.Applet
- implements Runnable
- ltFieldsgt
- ltMethodsgt
-
- The import clause is not necessary to use the
library. It is only a convenience. - An applet must be a subclass of
java.applet.Applet.
17The Applet Methods
- Public void init()... invoked when the applet
is loaded initially - public void start()... invoked when entering
the web page that contains the applet - public void stop()... invoked when leaving the
web page that contains the applet - public void run()... run the applet, i.e., the
main driver of the applet - public void paint(Graphics g)... paint the
picture
18The Life-Cycle of An Applet
19Fields and Initialization
protected Thread clockThread null protected
Font font new Font("Monospaced",
Font.BOLD, 48) protected Color color
Color.green By default all class fields are
automatically initialized to their default
values, usually 0 or null.
20The start() and stop() Methods
- public void start()
- if (clockThread null)
- clockThread new Thread(this)
- clockThread.start()
-
-
- public void stop()
- clockThread null
-
- Start and stop the thread.
- Stopped threads will not consume CPU time.
21The run() Method
- public void run()
- while (Thread.currentThread()
- clockThread)
- repaint()
- try
- Thread.currentThread().sleep(1000)
- catch (InterruptedException e)
-
-
- In each iteration, repaint() is invoked, then
sleep 1 second. - Sleep() must be invoked inside the try block.
22The paint() Method
public void paint(Graphics g) Calendar
calendar Calendar.getInstance() int hour
calendar.get(Calendar.HOUR_OF_DAY) int minute
calendar.get(Calendar.MINUTE) int second
calendar.get(Calendar.SECOND) g.setFont(font)
g.setColor(color) g.drawString(hour
"" minute / 10 minute 10 ""
second / 10 second 10, 10, 60)
23Who Calls run() And paint()?
- clockThread.start() calls DigitalClock.run()
- DigitalClock.repaint() calls
DigitalClock.paint() - The paint() method is usually not called
directly.
24Drawing Strings
g.drawString("A Sample String", x, y)
25HTML Source
lt!--DigitalClockDemo.html--gt lthtmlgt ltheadgt
lttitlegtDigital Clock Appletlt/titlegt
lt/headgt ltbody bgcolorwhitegt lth1gtThe Digital
Clock Appletlt/h1gtltpgt ltapplet codeDigitalClock.cla
ss width250 height80gt lt/appletgt ltpgtlthrgt
lta hrefDigitalClock.javagtThe sourcelt/agt lt/bodygt
lt/htmlgt
26The java.awt.Color Class
- Instances of the Color class represent colors.
- new Color(r, g, b)
- where r, g, b are the values of the red, green,
and blue components, respectively. They are
in the in the range of 0 to 255. - Some common colors are predefined as constants.
- black gray orange yellow
- blue green pink
- cyan lightGray red
- darkGray magenta white
27The java.awt.Font Class
- Fonts are specified with three attributes
- font name Serif Sans-serif Monospaced Dialog
DialogInput TimesRoman Helvetica Courier
Dialog - font style PLAIN BOLD ITALIC
- Styles can be combined Font.BOLDFont.ITALIC
- font size a positive integer
- A font can be created as follows
- new Font(name, style, size)
28Enahnced Digital Clock Applet
Setting applet parameters in the web page. The
applet tag in HTML ltapplet codeDigitalClock2.c
lass width250 height80gt ltparam namecolor
valuebluegt lt/appletgt Syntax ltapplet code
applet_class_file width width_in_pixel
height height_in_pixel gt ltparam name
param_name1 value param_value1 gt ... ltparam
name param_namen value param_valuen gt
lt/appletgt
29Getting Applet Parameters
import java.awt.Color public class
DigitalClock2 extends DigitalClock public
void init () String param
getParameter("color") if ("red".equals(param
)) color Color.red else if
("blue".equals(param)) color
Color.blue else if ("yellow".equals(param)
) color Color.yellow else if
("orange".equals(param)) color
Color.orange else color
Color.green
30The java.awt.Graphics Class
- Represent Graphics Context.
- A graphics context is an abstraction of various
drawing surfaces - screen
- printer
- off-screen image (an image stored in memory)
- Provide a rich set of graphics methods.
- drawString() drawLine()
- drawArc() fillArc()
- drawOval() fillOval()
- drawPolygon() fillPolygon()
- drawRect() fillRect()
- drawRoundRect() fillRoundRect()
31The java.awt.Graphics Class (cont'd)
Methods setColor(color) set the current
color setFont(font) set the current font
setPaintMode() set the paint, or overwrite
mode setXORMode(color) set the XOR mode
getColor() get the current color getFont()
get the current font getFontMetrics() get
the font metrics of the current font
getFontMetrics(font) get the font metrics for
the specified font
32The java.awt.FontMetrics Class
Methods getAscent() getDescent()
getHeight() getLeading() stringWidth(s)
33Scrolling Banner Applet
public class ScrollingBanner extends
java.applet.Applet implements Runnable
ltfield declarationsgt public void init()
... public void paint(Graphics g) ...
public void run() ... public void start()
... public void stop() ...
34Field Declarations
protected Thread bannerThread protected String
text protected Font font
new java.awt.Font("Sans-serif", Font.BOLD, 24)
protected int x, y protected int
delay 100 protected int offset
1 protected Dimension d
35Initialization
public void init() // get parameters "delay"
and "text" String att getParameter("delay")
if (att ! null) delay
Integer.parseInt(att) att
getParameter("text") if (att ! null)
text att else text "Scrolling
banner." // set initial position of the
text d getSize() x d.width y
font.getSize()
36(No Transcript)
37Paint the Current Frame
public void paint(Graphics g) // get the font
metrics to determine the length of the text
g.setFont(font)
FontMetrics fm g.getFontMetrics() int
length fm.stringWidth(text) // adjust the
position of text from the previous frame x -
offset // if the text is completely off to the
left end // move the position back to the right
end if (x lt -length) x d.width // set
the pen color and draw the background
g.setColor(Color.black)
g.fillRect(0,0,d.width,d.height) // set
the pen color, then draw the text
g.setColor(Color.green)
g.drawString(text, x, y)
38The start(), stop(), and run() Methods
public void start() bannerThread new
Thread(this) bannerThread.start() public
void stop() bannerThread null public
void run() while (Thread.currentThread()
bannerThread) try
Thread.currentThread().sleep(delay)
catch (InterruptedException e) repaint()
39How to Avoid Flickering?
- Flickering is caused by repaint()
- repaint() calls the update() method.
- The default update() method does the following
- paint the whole area with the background color
- set the foreground color
- call the paint() method.
- The update() method is also called by the system
to update windows. - Solution
- override the update() method
- use an off-screen image
40Using An Off-Screen Image
A.k.a. double-buffering import java.awt.
public class ScrollingBanner2 extends
ScrollingBanner protected Image image
// The off-screen image protected
Graphics offscreen // The
off-screen graphics public update(Graphics
g) ... public paint(Graphics g) ...
41Using An Off-Screen Image(cont'd)
public void update(Graphics g) // create
the offscreen image if it is the first time
if (image null) image
createImage(d.width, d.height) offscreen
image.getGraphics() // draw the
current frame into the off-screen image //
using the paint method of the superclass
super.paint(offscreen)
// copy the off-screen image to the screen
g.drawImage(image, 0, 0, this) public
void paint(Graphics g) update(g)
42Animation Applet Idiom
Category Behavioral implementation idiom.
Intent For an applet to continuously update its
appearance without user input or
intervention. Also known as Active Applet.
Applicability Use the Animation Applet Idiom to
animate dynamic processes.
43Animation Applet Idiom (cont'd)
public class AnimationApplet extends
java.applet.Applet implements Runnable
Thread mainThread null int delay public
void start() if (mainThread null)
mainThread new Thread(this)
mainThread.start() public void
stop() mainThread null
44Animation Applet Idiom (cont'd)
public void run() while (Thread.currentThre
ad() mainThread) repaint()
try Thread.currentThread().sleep(delay)
catch(InterruptedExceptione)
public void paint(java.awt.Graphics g)
ltpaint the current framegt ltother methods
and fieldsgt
45Another Applet -- Bouncing Ball
import java.awt. public class BouncingBall
extends java.applet.Applet implements Runnable
protected Color color Color.green
protected int radius 20 protected int x, y
protected int dx -2, dy -4
protected Image image protected Graphics
offscreen protected Dimension d //
...
46Bouncing Ball (cont'd)
public void init() String att
getParameter("delay") if (att ! null)
delay Integer.parseInt(att) d
getSize() x d.width 2 / 3 y
d.height - radius
47Bouncing Ball (cont'd)
public void update(Graphics g) // create
the off-screen image buffer // if it is
invoked the first time if (image null)
image createImage(d.width, d.height)
offscreen image.getGraphics() //
draw the background offscreen.setColor(Color.
white) offscreen.fillRect(0,0,d.width,d.heigh
t)
48Bouncing Ball (cont'd)
// adjust the position of the ball //
reverse the direction if it touches // any
of the four sides if (x lt radius x gt
d.width-radius) dx -dx
if (y lt radius y gt d.height-radius)
dy -dy x dx y dy
49Bouncing Ball (cont'd)
(method update() continued.) // draw
the ball offscreen.setColor(color)
offscreen.fillOval(x - radius, y - radius,
radius 2, radius 2) // copy
the off-screen image to the screen
g.drawImage(image, 0, 0, this) public
void paint(Graphics g) update(g)
50Bouncing Ball (cont'd)
// The animation applet idiom protected
Thread bouncingThread protected int delay
100 public void start() bouncingThread
new Thread(this) bouncingThread.start()
public void stop() bouncingThread
null
51Bouncing Ball (cont'd)
public void run() while
(Thread.currentThread()
bouncingThread) try
Thread.currentThread().sleep(delay)
catch (InterruptedException e)
repaint()
52Events
- An event is an instantaneous action
- Pressing a key
- Clicking a button on the mouse
- Selecting a menu item, etc.
- We need the program to respond to such events by
executing some routine(s) - Such interfaces are said to be event-driven
53Listener Objects
- The Java event model is based on the concept of
listeners. - A listener is an object whose sole purpose is
- To wait for an event to occur
- When the event does occur, the listener performs
(carries out) the appropriate behavior.
54Event Types and Objects
- There are two types of objects related to events
- event source (generates events)
- event listener (detects events)
- Action events are one of several type of events
- ENTER key event
- Mouse movement event
55Applet as a Listener Object
- The applet responds to the action event generated
by the inputLine object. The applet definition
must include - Import the Java event-handling package
- Implement the ActionListener class
- Define the method that will respond to the action
event generated - Register the applet object to the event source
object (inputLine)
56GreetingApplet
/ Program GreetingApplet An applet that
accepts the user's name and displays a
personalized greeting. / import
java.awt. import java.applet. import
java.awt.event.
public class GreetingApplet extends Applet
implements ActionListener
/ Data Members
/ private Label
prompt private Label greeting
private TextField inputLine
57GreetingApplet (Cont.)
/ Constructor
/ public GreetingApplet ()
// Create GUI objects prompt new
Label("Please enter your name") greeting
new Label() inputLine new
TextField(15) // add GUI objects to
the applet add(prompt)
add(inputLine) add(greeting)
// add this applet as an action listener
inputLine.addActionListener(this)
58GreetingApplet (Cont.)
/ Public methods void
actionPerformed( ActionEvent ) Method
actionPerformed Purpose Implements the
abstract method defined in the interface
ActionListener. The method retrieves the
text from the TextField object
inputLine and displays the personalized
greeting using the Label object greeting
Parameters ActionEvent object
Returns none / public void
actionPerformed(ActionEvent event)
greeting.setText("Nice to meet you, "
inputLine.getText() ".")
add(greeting) doLayout()
59Init Method
- Unlike conventional aplications, applets dont
have a main function. - Method init() is called after the applet object
has been constructed but before any other method
is called. - An applet is like a Jframe in that it has a
content pane that contains Swing components such
as buttons and text fields.