Download Basic Graphics Methods- Applets_1

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 2 Elementary Programming
(Continued - Pt. 4)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
1
Introduction to Graphics
Text or Graphics?
Scanner class: A program based on the methods in the
Scanner class is usually intended for a text-based
user interface.
Graphics class: In the java.awt package of libraries
the Graphics class is defined which contains
methods that allow for the design of a graphical
user interface.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Introduction to Graphics

The last few sections of each chapter of the textbook focus
on graphics and graphical user interfaces

A picture or drawing must be digitized for storage on a
computer

A picture is made up of pixels (picture elements), and each
pixel is stored separately

The number of pixels used to represent a picture is called
the picture resolution

The number of pixels that can be displayed by a monitor is
called the monitor resolution
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Coordinate Systems

Each pixel can be identified using a two-dimensional
coordinate system

When referring to a pixel in a Java program, we use a
coordinate system with the origin in the top-left corner
(0, 0)
112
X
40
(112, 40)
Y
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Representing Color

A black and white picture could be stored using one bit per
pixel (0 = white and 1 = black)

A colored picture requires more information; there are several
techniques for representing colors

For example, every color can be represented as a mixture of the
three additive primary colors Red, Green, and Blue

Each color is represented by three numbers between 0 and 255
that collectively are called an RGB value
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
RGB Color Combinations
Color is expressed as an RGB (red-green-blue) value because
our eyes have three types of color receptors that respond to
light that has some amount of one of those three primary
colors in it. The mixture of the different amounts of those
three colors creates different colors.
An RGB value of (255, 255, 0) maximizes the contribution
of red and green, and minimizes the contribution of blue,
which results in a bright yellow
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The Color Class

A color in a Java program is represented as an object created
from the Color class

The Color class also contains several predefined colors,
including the following:
Object
RGB Value
Color.black
Color.blue
Color.cyan
Color.green
Color.orange
Color.red
Color.white
Color.yellow
0, 0, 0
0, 0, 255
0, 255, 255
0, 255, 0
255, 200, 0
255, 0, 0
255, 255, 255
255, 255, 0
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The Color Class
 Other
Predefined Colors:
Object
RGB Value
Color.gray
Color.darkgray
Color.lightgray
Color.magenta
Color.pink
128, 128, 128
64, 64, 64
192, 192, 192
255, 0, 255
255, 175, 175
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Custom Colors
You can define Custom Colors by declaring your own Color object with
different RGB values as follows, where r,g,b are 3 values from 0 to 255:
Color theColor = new Color(r,g,b);
The above statement declares “theColor” to be a variable object (instead
of a primitive) with Color as its type. The term “new” means that a new
instance of the object will be created with the specified values. This is
called “instantiation” and is done for many other types of objects as well.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Applets

A Java application is a stand-alone program with a main
method (like the ones we've seen so far)

A Java applet is a program that is intended to transported
over the Web and executed using a web browser

An applet also can be executed using the appletviewer tool
of the Java Software Development Kit (and available in
jGRASP)

An applet doesn't have a main method

Instead, there are several special methods that serve specific
purposes
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
java.applet.Applet
An applet is a Java class that runs in a Web browser. Whereas a
stand-alone Java application uses the main() function as its
cornerstone, the architecture and life cycle of an applet is more
complex. Also, since applets are routinely packaged with HTML
pages that are downloaded from the Web, they represent
significant security issues.
The class Applet shares much commonality with the class
Frame. The common ancestries are portrayed below.
Object
+--- Component
+--- Container
|
+--- Window
|
+--- Frame
|
+--- Panel
+--- Applet
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
11
Applets

The paint method, for instance, is executed
automatically and is used to draw the applet’s contents

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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Applets

For an Applet to function correctly, it must have certain
methods and properties that allow it to communicate with
the browser

To ensure that your program has the right methods and
properties you need to have your program access predefined
versions of those methods and properties that already exists
in other classes. This is done by “inheriting” from what is
needed from those other classes

The following is an example of an applet that draws shapes
on the screen and then puts a quote from Albert Einstein on
top of the shapes:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The Einstein Applet:
import java.applet.Applet;
import java.awt.Graphics;
// The Applets library
// The Graphics library
public class Einstein extends Applet
{
// Draws a quotation by Albert Einstein among some shapes.
public void paint (Graphics page)
{
page.drawRect (50, 50, 40, 40); // square
page.drawRect (60, 80, 225, 30); // rectangle
page.drawOval (75, 65, 20, 20); // circle
page.drawLine (35, 60, 100, 120); // line
page.drawString ("Out of clutter, find simplicity.", 110, 70);
page.drawString ("-- Albert Einstein", 130, 100);
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Applets

The reserved word extends is used in Java when a program
inherits from another class

To work properly an applet can inherit from the Applet
class or the JApplet class (we will discuss the differences
later)

An applet is embedded into an HTML file using a tag that
references the bytecode file of the applet

The bytecode version of the program is transported across
the web and executed by a Java interpreter that is part of the
browser. The following is an example of an HTML file that
executes the Einstein applet in a web browser:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Java.awt
The Java programming language class library provides a user
interface toolkit AWT which stands for Abstract Window Toolkit.
The AWT is part of the Java Foundation Classes (JFC) -- the
standard API for providing graphical user interfaces (GUIs) for
Java programs.
The AWT is both powerful and flexible. The class and method
descriptions found in the distributed documentation provide little
guidance for the new programmer.
•Below is the package java.awt link
http://download.oracle.com/javase/1.4.2/docs/api/java/awt/package-summary.html
AWT Components:
The class component is extended by all the AWT components. More of the codes can be put to
this class to design lot of AWT components. Following are the AWT components:
Canvas, Checkbox, Labels, Buttons, Scrollbar, TextField
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
16
An HTML File using the
Applet Tag
<html>
<head>
<title>The Einstein Applet</title>
</head>
<body>
<applet code="Einstein.class" width=350 height=175>
</applet>
</body>
</html>
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The Java Headers
To create a new class that uses things from another class, you
must access the files (or libraries) with the other class details
using the “import” command if they are not in the same
directory or folder as the new class. The following shows how
this is done in the case of the Applet class for a Snowman
drawing program:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
public class Snowman extends Applet
{
// Draws a Snowman
public void paint (Graphics page)
{
…
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Drawing 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

Shapes with curves, like an oval, are usually drawn by
specifying the shape’s bounding rectangle

An arc can be thought of as a section of an oval
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Drawing a Line
10
150
20
45
Y
page.drawLine (10, 20, 150, 45);
or
page.drawLine (150, 45, 10, 20);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
X
Drawing a Rectangle
50
X
20
40
100
Y
page.drawRect (50, 20, 100, 40);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Drawing an Oval
175
X
20
80
bounding
rectangle
Y
50
page.drawOval (175, 20, 50, 80);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Drawing Shapes
 Every
drawing surface has a background
color
 Every
graphics context has a current
foreground color
 Both
can be set explicitly
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Drawing Shapes
In the Graphics class the following methods are
available for drawing certain shapes, as further
explained in the following slides:
drawLine(x1,y1,x2,y2)
drawRect(x,y,width,height)
drawOval(x,y,width,height)
drawArc(x,y,width,height,startAngle,arcAngle)
drawString(String,x,y)
fillRect(x,y,width,height)
fillOval(x,y,width,height)
fillArc(x,y,width,height,startAngle,arcAngle)
setColor(Color)
getColor()
setBackground(Color)
=> global, so no Graphics page involved.
getBackground()
=> global, so no Graphics page involved.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
Drawing Shapes
void drawLine(int x1, int y1, int x2, int y2)
Paints a line from point (x1,y1) to point (x2,y2) using the
foreground color.
Ex:
page.drawLine(10,10,50,50)
// The above draws a line from (10,10) to (50,50)
void drawRect(int x, int y, int width, int height)
Paints a rectangle with upper left corner (x,y) and dimensions
width and height using the foreground color.
Ex:
page.drawRect(10,10,40,40)
// The above draws a 40 x 40 square with the top left point
// being located at (10,10)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
7-25
Drawing Shapes
void drawOval(int x, int y, int width, int height)
Paints an oval bounded by the rectangle with upper left corner of
(x,y) and dimensions width and height using the foreground color.
Ex:
page.drawOval(10,10,40,40)
// The above draws a circle with a diameter of 40 with the
// top left point of its bounded rectangle being at (10,10)
void drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle)
Paints an arc along the oval bounded by the rectangle defined by
x, y, width and height using the foreground color. The arc starts at
startAngle and extends for a distance defined by arcAngle.
Ex:
page.drawArc(10,10,40,40,45,90)
// Draws 90o arc of the earlier circle starting at 45o up
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
7-26
Drawing Shapes
void drawString(String str, int x, int y)
Paints the character string, str, starting right above point (x,y) and
extending to the right using the foreground color.
Ex:
page.drawString("Hello World",20,20)
// Draws “Hello World” beginning at point (20,20)
void fillRect(int x, int y, int width, int height)
Fills in the rectangle defined by x, y, width and height using the
foreground color.
Ex:
page.fillRect(10,10,40,40)
// Fills in the defined rectangle with the current foreground
// color
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
7-27
Drawing Shapes
void fillOval(int x, int y, int width, int height)
Fills in an oval bounded by the rectangle with upper left corner of
(x,y) and dimensions width and height using the foreground color.
Ex:
page.fillOval(10,10,40,40)
// Fills in the circle defined by the arguments with the
// foreground color
void fillArc(int x, int y, int width, int height, int startAngle,
int arcAngle)
Fills in an arc along the oval bounded by the rectangle defined by
x, y, width and height using the foreground color. The arc starts at
startAngle and extends for a distance defined by arcAngle.
Ex:
page.drawArc(10,10,40,40,45,90)
// Fills in the defined arc with the current foreground color
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
7-28
Drawing Shapes
void setColor(Color color)
Sets the foreground color to the specified color.
Ex: page.setColor(Color.blue) // Sets foreground color to blue
Color getColor()
Returns the foreground color.
Ex: theColor = page.getColor() // theColor gets foreground color
void setBackground(Color color)
Sets the global background color. No graphics object is involved.
Ex: page.setBackground(Color.red) // Sets background to red
Color getBackground()
Returns the global background color. No graphics object involved.
Ex: theColor = getBackground() // theColor gets background color
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
7-29
The HappyFace Applet Source Code:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
// The Applets library
// The Graphics library
// The Color library
public class HappyFace extends Applet
{
// An Applet that draws a happy face.
public void paint (Graphics page)
{
page.setColor(Color.BLACK); // the drawing color
page.drawOval (100, 70, 200, 200); // the outline of the face
page.fillOval (155, 120, 10, 20); // the first eye
page.fillOval (230, 120, 10, 20); // the second eye
page.drawArc (150, 195, 100, 50, 180, 180); // the smile
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The HappyFace Graphics Applet
Sample
screen
output
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Drawing Arcs

The drawArc method draws an arc.
drawArc(100, 50, 200, 200, 180, 180);

The drawArc method takes six arguments.
– The first four arguments are the same as the four
arguments needed by the drawOval method.
– The last two arguments indicate where the arc starts,
and the number of degrees through which is sweeps.
– 0 degrees is horizontal and to the right.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Specifying an Arc
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Specifying an Arc
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Drawing Shapes
In the Graphics class the following methods are available for drawing certain shapes, as further
explained in the following slides:
drawLine(x1,y1,x2,y2)
drawRect(x,y,width,height)
drawOval(x,y,width,height)
drawArc(x,y,width,height,startAngle,arcAngle)
drawString(String,x,y)
fillRect(x,y,width,height)
fillOval(x,y,width,height)
fillArc(x,y,width,height,startAngle,arcAngle)
setColor(Color)
getColor()
setBackground(Color)
=> global, so no Graphics page involved.
getBackground()
=> global, so no Graphics page involved.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
Drawing Shapes
void drawLine(int x1, int y1, int x2, int y2)
Paints a line from point (x1,y1) to point (x2,y2) using the
foreground color.
Ex:
page.drawLine(10,10,50,50)
// The above draws a line from (10,10) to (50,50)
void drawRect(int x, int y, int width, int height)
Paints a rectangle with upper left corner (x,y) and dimensions
width and height using the foreground color.
Ex: page.drawRect(10,10,40,40)
// The above draws a 40 x 40 square with the top left point
// being located at (10,10)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
7-36
Drawing Shapes
void drawOval(int x, int y, int width, int height)
Paints an oval bounded by the rectangle with upper left corner of
(x,y) and dimensions width and height using the foreground color.
Ex:
page.drawOval(10,10,40,40)
// The above draws a circle with a diameter of 40 with the
// top left point of its bounded rectangle being at (10,10)
void drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle)
Paints an arc along the oval bounded by the rectangle defined by
x, y, width and height using the foreground color. The arc starts at
startAngle and extends for a distance defined by arcAngle.
Ex:
page.drawArc(10,10,40,40,45,90)
// Draws 90o arc of the earlier circle starting at 45o up
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
7-37
Drawing Shapes
void drawString(String str, int x, int y)
Paints the character string, str, starting right above point (x,y) and
extending to the right using the foreground color.
Ex:
page.drawString("Hello World",20,20)
// Draws “Hello World” beginning at point (20,20)
void fillRect(int x, int y, int width, int height)
Fills in the rectangle defined by x, y, width and height using the
foreground color.
Ex: page.fillRect(10,10,40,40)
// Fills in the defined rectangle with the current foreground
// color
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
7-38
Drawing Shapes
void fillOval(int x, int y, int width, int height)
Fills in an oval bounded by the rectangle with upper left corner of
(x,y) and dimensions width and height using the foreground color.
Ex:
page.fillOval(10,10,40,40)
// Fills in the circle defined by the arguments with the
// foreground color
void fillArc(int x, int y, int width, int height, int startAngle,
int arcAngle)
Fills in an arc along the oval bounded by the rectangle defined by
x, y, width and height using the foreground color. The arc starts at
startAngle and extends for a distance defined by arcAngle.
Ex:
page.drawArc(10,10,40,40,45,90)
// Fills in the defined arc with the current foreground color
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
7-39
Drawing Shapes
void setColor(Color color)
Sets the foreground color to the specified color.
Ex: page.setColor(Color.blue) // Sets foreground color to blue
Color getColor()
Returns the foreground color.
Ex: theColor = page.getColor() // theColor gets foreground color
void setBackground(Color color)
Sets the global background color. No graphics object is involved.
Ex: page.setBackground(Color.red) // Sets background to red
Color getBackground()
Returns the global background color. No graphics object involved.
Ex: theColor = getBackground() // theColor gets background color
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
7-40
Drawing Shapes
The Graphics object passed to the paint method has a
boundary rectangle that you can access with the
getClipBounds() method, which returns a rectangle. The
rectangle object has x, y, width and height as its integer
fields. For example, to get the width and height of the
graphics screen, you could do the following:
Rectangle theRect;
theRect = page.getClipBounds();
// Now theRect.width stores the width of the graphics screen and
// theRect.height stores the height of the graphics screen.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
7-41
Drawing Arcs

The drawArc method draws an arc.
drawArc(100, 50, 200, 200, 180, 180);

The drawArc method takes six arguments.
– The first four arguments are the same as the four
arguments needed by the drawOval method.
– The last two arguments indicate where the arc starts,
and the number of degrees through which is sweeps.
– 0 degrees is horizontal and to the right.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Polygons

Any multi-sided, closed shape can be drawn using the Polygon
class of the java.awt package by providing the vertices (points) in
the shape. The Graphics class methods drawPolygon() and
fillPolygon() take a single Polygon object as a parameter.

For instance, a three sided shape that had vertices at the three
points (x1,y1), (x2,y2) and (x3,y3) would be drawn like so:
Polygon poly = new Polygon();
poly.addPoint (x1,y1);
poly.addPoint (x2,y2);
poly.addPoint (x3,y3);
page.drawPolygon (poly);

See House.java where the roof is a Polygon.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Images

You can use the Image class from the java.awt package to
display JPEG, PNG and GIF images (as well as BMP others).
An Image object is drawn using the drawImage() Graphics class
method at an (x,y) coordinate, and it can be resized as well.

In an Applet, you load an image using the getImage() and
getCodeBase() methods of the JApplet or Applet class like so:
Image car = getImage(getCodeBase(),"car.gif");

In an Applet, you must load the image from the init() method:
private image car;
public void init() {
car = getImage(getCodeBase(),"car.gif");
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Images

If your program is a Standard Java Application and not an
Applet, then you cannot use the Applet’s getImage() and
getCodeBase() methods. Instead you use the getImage() method
of the ImageIcon class of the java.swing package like so:
Image car = new ImageIcon("car.gif").getImage();

In an Application you don’t use the init() method to load your
image, you can load it at any place in your program.

In Eclipse, images for an Application are placed inside your
project folder. For an Applet images are placed inside your bin
folder that is inside your project folder. You can also put them in
a subfolder in those folders like so:
Image car = new ImageIcon("images/car.gif").getImage();
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Positioning and Resizing Images

You display the image object at position (40,20) as its top left corner in
the current Graphics object (which we will call “page” but you can give it
other names) using the following page.drawImage() method:
page.drawImage(car,40,20,null);

To resize an image you just add the width and height dimensions right
after the x and y coordinates of the top left corner:
page.drawImage(car,40,20,60,30,null);

This would still position the car image at (40,20) as its top left corner, but
now the image would be drawn 60 pixels wide and 30 pixels high. If you
don’t resize it, it is drawn with its normal width and height.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Waiting for Images to Load

Whether your program is an Applet or an Application, when you
call the getImage() method in Java, it returns immediately, and
does not wait until the image is fully loaded, which means your
image might not show up when you first draw the image. This
can be very problematic, so you can use the MediaTracker class
of the java.awt package to wait until the image is completely
loaded before attempting to draw it. You do this like so:
car = getImage(getCodeBase(),"car.gif");
// or car = new ImageIcon("car.gif").getImage();
MediaTracker track = new MediaTracker(this);
track.addImage(car,0);
try {
track.waitForAll(); // wait until loading is finished
} catch (InterruptedException e) {}

See HouseCar.java
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Animation

Applets and Applications use the Graphics object to draw an
image. The image is usually drawn inside the paint() method in
an Applet, and inside the paintComponent() method in an
Application, both of which receive a Graphics object as their
paramater.

An animation can be created when you repeatedly move the x or
the y coordinate of the image you are drawing like so (for a
Graphics object given the name “page” here):
page.drawImage(car,x,y,null);
page.drawImage(car,x+10,y,null);
page.drawImage(car,x+20,y,null);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Animation

To make this work, you must repeatedly restore the background
and all other drawings done by the paint() or paintComponent()
method when redrawing the image. This means you cannot put
the multiple drawing commands with changed coordinates inside
the paint() or paintComponent(). You need to modify the
coordinates in a different method and then invoke the paint() or
paintComponent() methods making the call:
repaint();

You also need a pause between each drawing to make this work,
because if you do not pause between each step the motion would
go to fast for the eye to see and the steps would appear to happen
simultaneously.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Pausing During Animation

A loop can execute thousands of instructions within
a second, so when you use a loop in an animation,
the pictures may be drawn too quickly. So you need
to pause between frames, but how long should you
pause?

Our eyes can see between 25 to 40 frames per
second (fps) – 40 fps is about 1 frame every 25
milliseconds (ms) and 25 fps is about 1 frame ever
40 ms– so you need to pause for at least 40 ms or
less to create the illusion of smooth motion.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Animation with the Timer

The Timer class is from the javax.swing package and it fires an
ActionEvent at a specified delay (time interval). That means that at a
specified interval you can update the animation like so:
private Timer timer;
public void init() {
timer = new Timer(40,this); // setting time interval to 40 milliseconds
timer.start();
// start the timer
}
public void actionPerformed (ActionEvent evt) { // this method runs every 40 milliseconds
xPos += 5;
// move the x position of the car
repaint();
// redraw the window
}


The above code will moves the car by 5 pixels every 40 milliseconds
and redraws the screen with each move.
See HouseCarAnimate.java
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Animation Issues

The best images to use for animation when you have a background
is an image that is transparent, like a transparent GIF or PNG.
This is because the background will show through the image
wherever the image has a place in it for the background to show
through.

A Graphics Image is always in a rectangular frame when drawn,
and if the image is not a picture of a solid rectangle, some part of
the image will not be shown in that rectangle. When the image
has transparency, the background will show in those missing parts
in the rectangular frame, and it will look more natural.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807