SlideShare a Scribd company logo
1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Multithreaded
Graphics
Multithreaded Graphics2 www.corewebprogramming.com
Agenda
• Approaches for multithreaded graphics
– Redraw everything in paint
– Have routines other than paint draw directly on window
– Override update and have paint do incremental updating
– Double buffering
• Reducing flicker in animations
• Implementing double buffering
• Animating images
• Controlling timers
Multithreaded Graphics3 www.corewebprogramming.com
Multithreaded Graphics:
Alternative Approaches
• Redraw everything in paint
– Simple and easy, but if things change quickly it is slow and can
result in a flickering display
• Have routines other than paint directly do drawing
operations
– Easy, efficient, and flicker-free, but results in “transient” drawing
that is lost next time the screen is redrawn
• Override update and have paint do incremental
updating
– Eliminates the flicker and improves efficiency somewhat, but
requires the graphics to be non-overlapping
• Double buffering
– Most efficient option and has no problem with overlapping graphics.
– More complex and requires additional memory resources
Multithreaded Graphics4 www.corewebprogramming.com
Redraw Everything in paint
• Idea
– Have user actions change non-graphical data structures,
then call repaint.
– The repaint method sets a flag that tells the event-
handling process to call update.
– The standard update method clears the screen and then
calls paint.
– The paint method completely redraws everything.
• Advantage
– Easy
• Disadvantages
– Flickers, slow.
Multithreaded Graphics5 www.corewebprogramming.com
Redrawing Everything in
paint: Example
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
/** Applet that draws a small circle where you click. */
public class DrawCircles extends Applet {
private Vector circles;
public void init() {
circles = new Vector();
addMouseListener(new CircleDrawer());
setBackground(Color.white);
}
...
Multithreaded Graphics6 www.corewebprogramming.com
Redrawing Everything in paint:
Example (Continued)
/** When you click the mouse, create a SimpleCircle,
* put it in the Vector, and tell the system
* to repaint (which calls update, which clears
* the screen and calls paint).
*/
private class CircleDrawer extends MouseAdapter {
public void mousePressed(MouseEvent event) {
circles.addElement(new SimpleCircle(event.getX(),
event.getY(),
25));
repaint();
}
}
Multithreaded Graphics7 www.corewebprogramming.com
Redrawing Everything in paint:
Example (Continued)
...
/** This loops down the available SimpleCircle
* objects, drawing each one.
*/
public void paint(Graphics g) {
SimpleCircle circle;
for(int i=0; i<circles.size(); i++) {
circle = (SimpleCircle)circles.elementAt(i);
circle.draw(g);
}
}
}
Multithreaded Graphics8 www.corewebprogramming.com
Redrawing Everything in
paint: Example (Continued)
public class SimpleCircle {
private int x, y, radius;
public SimpleCircle(int x, int y, int radius) {
setX(x);
setY(y);
setRadius(radius);
}
/** Given a Graphics, draw the SimpleCircle
* centered around its current position.
*/
public void draw(Graphics g) {
g.fillOval(x - radius, y - radius,
radius * 2, radius * 2);
}
...
}
Multithreaded Graphics9 www.corewebprogramming.com
Redrawing everything in paint:
Result
By storing results in a permanent data structure and redrawing the whole structure every
time paint is invoked, you cause the drawing to persist even after the window is covered
up and reexposed
Multithreaded Graphics10 www.corewebprogramming.com
Have Other Routines Draw
Directly on Window
• Idea
– Arbitrary methods (i.e., other than paint) can call
getGraphics to obtain the window’s Graphics object
– Use that Graphics object to draw
– Drawing lost if
• Window covered up and reexposed
• The update method called (e.g., via repaint)
• Advantage
– Fast
• Disadvantage
– Temporary
Multithreaded Graphics11 www.corewebprogramming.com
Drawing Directly on Window:
Example
public class Rubberband extends Applet {
private int startX, startY, lastX, lastY;
...
private void drawRectangle(Graphics g, int startX,
int startY, int stopX, int stopY ) {
int x, y, w, h;
x = Math.min(startX, stopX);
y = Math.min(startY, stopY);
w = Math.abs(startX - stopX);
h = Math.abs(startY - stopY);
g.drawRect(x, y, w, h);
}
...
private class RectRecorder extends MouseAdapter {
public void mousePressed(MouseEvent event) {
startX = event.getX();
startY = event.getY();
lastX = startX;
lastY = startY;
}
Multithreaded Graphics12 www.corewebprogramming.com
Drawing Directly on Window:
Example (Continued)
public void mouseReleased(MouseEvent event) {
Graphics g = getGraphics();
g.setXORMode(Color.lightGray);
drawRectangle(g, startX, startY, lastX, lastY);
}
}
private class RectDrawer extends MouseMotionAdapter {
public void mouseDragged(MouseEvent event) {
int x = event.getX();
int y = event.getY();
Graphics g = getGraphics();
g.setXORMode(Color.lightGray);
drawRectangle(g, startX, startY, lastX, lastY);
drawRectangle(g, startX, startY, x, y);
lastX = x;
lastY = y;
}
}
}
Multithreaded Graphics13 www.corewebprogramming.com
Drawing Directly on Window:
Result
By retrieving the Graphics object, methods other than paint
can draw directly on the window
Multithreaded Graphics14 www.corewebprogramming.com
Override update and Have
paint do Incremental Updating
• Idea
– Have repaint (which triggers update) avoid clearing the
screen each time by overriding update as follows:
public void update(Graphics g) {
paint(g);
}
– Then, assuming objects don’t overlap, erase each object
at its old location by drawing over it in the background
color then drawing it at the new location
• Advantages
– No flicker, faster
• Disadvantage
– Fails for overlapping images
Multithreaded Graphics15 www.corewebprogramming.com
Incremental Updating:
Bounce Applet
public class Bounce extends Applet
implements Runnable, ActionListener {
private Vector circles;
private int width, height;
private Button startButton, stopButton;
private Thread animationThread = null;
...
public void actionPerformed(ActionEvent event) {
if (event.getSource() == startButton) {
if (circles.size() == 0) {
// Erase any circles from previous run.
getGraphics().clearRect(0, 0, getSize().width,
getSize().height);
animationThread = new Thread(this);
animationThread.start();
}
int radius = 25;
int x = radius + randomInt(width - 2 * radius);
int y = radius + randomInt(height - 2 * radius);
int deltaX = 1 + randomInt(10);
int deltaY = 1 + randomInt(10);
circles.addElement(new MovingCircle(x, y, radius,
deltaX, deltaY));
Multithreaded Graphics16 www.corewebprogramming.com
Bounce Applet (Continued)
} else if (event.getSource() == stopButton) {
if (animationThread != null) {
animationThread = null; // Stop animation
circles.removeAllElements();
}
}
repaint();
}
public void run() {
Thread myThread = Thread.currentThread();
// Really while animationThread not null
while(animationThread == myThread) {
repaint();
pause(100);
}
}
...
Multithreaded Graphics17 www.corewebprogramming.com
Bounce Applet (Continued)
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
MovingCircle circle;
for(int i=0; i<circles.size(); i++) {
circle = (MovingCircle)circles.elementAt(i);
g.setColor(getBackground());
circle.draw(g); // Old position
circle.move(width, height);
g.setColor(getForeground());
circle.draw(g); // New position
}
}
...
}
Multithreaded Graphics18 www.corewebprogramming.com
Incremental Updating:
MovingCircle Class
public class MovingCircle extends SimpleCircle {
private int deltaX, deltaY;
...
public void move(int windowWidth, int windowHeight) {
setX(getX() + getDeltaX());
setY(getY() + getDeltaY());
bounce(windowWidth, windowHeight);
}
private void bounce(int windowWidth, int windowHeight) {
int x = getX(), y = getY(), radius = getRadius(),
deltaX = getDeltaX(), deltaY = getDeltaY();
if ((x - radius < 0) && (deltaX < 0))
setDeltaX(-deltaX);
else if ((x + radius > windowWidth) && (deltaX > 0))
setDeltaX(-deltaX);
if ((y -radius < 0) && (deltaY < 0))
setDeltaY(-deltaY);
else if((y + radius > windowHeight) && (deltaY > 0))
setDeltaY(-deltaY);
}
...
}
Multithreaded Graphics19 www.corewebprogramming.com
Incremental Updating, Result
Incremental updating from paint can be flicker free and
relatively fast, but it does not easily handle overlapping items
Multithreaded Graphics20 www.corewebprogramming.com
Option 4: Double Buffering
• Idea
– Draw into an off-screen pixmap, then draw that pixmap on window
• Outline
1. Override update to simply call paint
• This prevents the flicker that would normally occur each time
update clears the screen before calling paint
2. Allocate an Image using createImage
• Note that since this image uses native window-system support,
it cannot be done until a window actually appears
3. Look up its Graphics object using getGraphics
• Unlike with windows, where you need to look up the Graphics
context each time you draw, with images it is reliable to look it
up once, store it, and reuse the same reference thereafter
4. For each step, clear the image and redraw all objects onto it
• Dramatically faster than drawing onto a visible window
5. Draw the offscreen image onto the window
• Use drawImage
Multithreaded Graphics21 www.corewebprogramming.com
Double Buffering: Pros & Cons
• Advantages
– Much faster
– Can easily handle overlapping objects
• Disadvantages
– More complex
– Memory requirements for offscreen pixmap
– Sometimes less incremental update of display
Multithreaded Graphics22 www.corewebprogramming.com
Double Buffering: Example
public class DoubleBufferBounce extends Applet implements
Runnable, ActionListener {
private Vector circles;
private int width, height;
private Image offScreenImage;
private Graphics offScreenGraphics;
private Button startButton, stopButton;
private Thread animationThread = null;
public void init() {
setBackground(Color.white);
width = getSize().width;
height = getSize().height;
offScreenImage = createImage(width, height);
offScreenGraphics = offScreenImage.getGraphics();
// Automatic in some systems, not in others.
offScreenGraphics.setColor(Color.black);
circles = new Vector();
...
}
Multithreaded Graphics23 www.corewebprogramming.com
Double Buffering: Example
public void run() {
MovingCircle circle;
Thread myThread = Thread.currentThread();
// Really while animationThread not null.
while(animationThread == myThread) {
for(int j=0; j<circles.size(); j++) {
circle = (MovingCircle)circles.elementAt(j);
circle.move(width, height);
}
repaint();
pause(100);
}
}
public void paint(Graphics g) {
offScreenGraphics.clearRect(0, 0, width, height);
MovingCircle circle;
for(int i=0; i<circles.size(); i++) {
circle = (MovingCircle)circles.elementAt(i);
circle.draw(offScreenGraphics);
}
g.drawImage(offScreenImage, 0, 0, this);
}
}
Multithreaded Graphics24 www.corewebprogramming.com
Double Buffering: Result
At the expense of memory and some complexity, double buffering allows fast,
flicker-free updating of possibly overlapping images
Multithreaded Graphics25 www.corewebprogramming.com
Array-Based Animation
• Idea
– Load a sequence of images into an array
– Start a thread to cycle through the images and draw to the
graphics object
• Each time the thread loops through the while loop,
the array index is incremented and repaint (which
triggers update) is called to update the images on the
screen
– Stop the animation by setting a flag
• In an applet, end the animation from the applet’s stop
method
Multithreaded Graphics26 www.corewebprogramming.com
Array-Based Animation:
Example
public class ImageAnimation extends Applet {
private static final int NUMDUKES = 2;
private Duke[] dukes; // Duke has array of images
private int i;
public void init() {
dukes = new Duke[NUMDUKES];
setBackground(Color.white);
}
public void start() {
int tumbleDirection;
for (int i=0; i<NUMDUKES ; i++) {
tumbleDirection = (i%2 == 0) ? 1 :-1;
dukes[i] = new Duke(tumbleDirection, this);
dukes[i].start();
}
}
...
Multithreaded Graphics27 www.corewebprogramming.com
Animation Example (Continued)
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
for (i=0 ; i<NUMDUKES ; i++) {
if (dukes[i] != null) {
g.drawImage(Duke.images[dukes[i].getIndex()],
200*i, 0, this);
}
}
}
public void stop() {
for (int i=0; i<NUMDUKES ; i++) {
if (dukes[i] != null) {
dukes[i].setState(Duke.STOP);
}
}
}
}
Multithreaded Graphics28 www.corewebprogramming.com
Animation Example (Continued)
public class Duke extends Thread {
...
public static Image[] images;
private static final int NUMIMAGES = 15;
private static Object lock = new Object();
private int state = RUN;
public Duke(int tumbleDirection, Applet parent) {
this.tumbleDirection = tumbleDirection;
this.parent = parent;
synchronized(lock) {
if (images == null) { // If not previously loaded.
images = new Image[ NUMIMAGES ];
for (int i=0; i<NUMIMAGES; i++) {
images[i] = parent.getImage( parent.getCodeBase(),
"images/T" + i + ".gif");
}
}
}
}
...
Multithreaded Graphics29 www.corewebprogramming.com
Animation Example (Continued)
public void run() {
while (checkState()!=STOP) {
index += tumbleDirection;
if (index < 0) {
index = NUMIMAGES - 1;
} else if (index >= NUMIMAGES) {
index = 0;
}
parent.repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break; // Break while loop.
}
}
}
}
Multithreaded Graphics30 www.corewebprogramming.com
Animation: Result
Duke is a registered trademark of Sun Microsystems, Inc.
All restrictions apply (http://www.sun.com/policies/trademarks/).
Used with permission.
Multithreaded Graphics31 www.corewebprogramming.com
Timers
• Swing defines a Timer class
– A Timer can ring for a single cycle or fire periodically
– At each ring an ActionEvent is fired
– Useful for animations, simulations, and timing out secure
network connections
• Approach
Timer timer = new Timer(milliseconds, listener);
timer.start();
...
...
timer.stop();
Multithreaded Graphics32 www.corewebprogramming.com
Useful Timer Methods
• start/stop
– Starts or stops the timing sequence
• restart
– Cancels any undelivered time events and starts the timer again
• setCoalesce
– Turns coalescing off or on
– By default, if a timer event is in the event queue (coalesce
true), a new ActionEvent is not created at the next firing
interval
• setRepeats
– Sets the timer to ring once (false) or to ring periodically (true)
– Default behavior is to ring periodically
Multithreaded Graphics33 www.corewebprogramming.com
Timer: Example
import java.awt.*;
import javax.swing.*;
public class TimedAnimation extends JApplet {
private static final int NUMDUKES = 2;
private TimedDuke[] dukes;
private int i, index;
public void init() {
dukes = new TimedDuke[NUMDUKES];
setBackground(Color.white);
dukes[0] = new TimedDuke( 1, 100, this);
dukes[1] = new TimedDuke(-1, 500, this);
}
// Start each Duke timer.
public void start() {
for (int i=0; i<NUMDUKES ; i++) {
dukes[i].start();
}
} ...
Multithreaded Graphics34 www.corewebprogramming.com
Timer Example (Continued)
...
public void paint(Graphics g) {
for (i=0 ; i<NUMDUKES ; i++) {
if (dukes[i] != null) {
index = dukes[i].getIndex();
g.drawImage(TimedDuke.images[index], 200*i, 0, this);
}
}
}
// Stop each Duke timer.
public void stop() {
for (int i=0; i<NUMDUKES ; i++) {
dukes[i].stop();
}
}
}
Multithreaded Graphics35 www.corewebprogramming.com
Timer Example (Continued)
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TimedDuke extends Timer
implements ActionListener {
private static final int NUMIMAGES = 15;
private static boolean loaded = false;
private static Object lock = new Object();
private int tumbleDirection;
private int index = 0;
private Applet parent;
public static Image[] images = new Image[NUMIMAGES];
public TimedDuke(int tumbleDirection, int msec,
Applet parent) {
super(msec, null);
addActionListener(this);
this.tumbleDirection = tumbleDirection;
this.parent = parent; ...
Multithreaded Graphics36 www.corewebprogramming.com
Timer Example (Continued)
synchronized (lock) {
if (!loaded) {
// Load images using MediaTracker
...
}
}
}
// Return current index into image array.
public int getIndex() { return index; }
// Receives timer firing event. Increments the index into
// image array and forces repainting of the new image.
public void actionPerformed(ActionEvent event) {
index += tumbleDirection;
if (index < 0){
index = NUMIMAGES - 1;
}
if (index >= NUMIMAGES) {
index = 0;
}
parent.repaint();
}
}
Multithreaded Graphics37 www.corewebprogramming.com
Timer Example: Result
Each Duke moves at a different speed
Duke is a registered trademark of Sun Microsystems, Inc.
All restrictions apply (http://www.sun.com/policies/trademarks/).
Used with permission.
Multithreaded Graphics38 www.corewebprogramming.com
Summary
• Options
– Redraw everything in paint
– Have routines other than paint directly do drawing
operations
– Override update and have paint do incremental updating
– Double buffering
• Animation can be achieved by cycling through
a sequence of images
• Timers are restartable threads that fire an
ActionEvent once or periodically
39 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Questions?

More Related Content

What's hot

Enhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsEnhancing UI/UX using Java animations
Enhancing UI/UX using Java animations
Naman Dwivedi
 
Android UI Tips & Tricks
Android UI Tips & TricksAndroid UI Tips & Tricks
Android UI Tips & Tricks
DroidConTLV
 
YUI Evolved
YUI EvolvedYUI Evolved
YUI Evolved
Michael Smith Jr.
 
HTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web GamesHTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web Games
livedoor
 
WebGL 3D player
WebGL 3D playerWebGL 3D player
WebGL 3D player
Vasilika Klimova
 
Kotlin Mullets
Kotlin MulletsKotlin Mullets
Kotlin Mullets
James Ward
 
3d game engine
3d game engine3d game engine
3d game engine
luisfvazquez1
 
Hadoop meetup 2014
Hadoop meetup 2014Hadoop meetup 2014
Hadoop meetup 2014
dudaspm
 

What's hot (8)

Enhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsEnhancing UI/UX using Java animations
Enhancing UI/UX using Java animations
 
Android UI Tips & Tricks
Android UI Tips & TricksAndroid UI Tips & Tricks
Android UI Tips & Tricks
 
YUI Evolved
YUI EvolvedYUI Evolved
YUI Evolved
 
HTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web GamesHTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web Games
 
WebGL 3D player
WebGL 3D playerWebGL 3D player
WebGL 3D player
 
Kotlin Mullets
Kotlin MulletsKotlin Mullets
Kotlin Mullets
 
3d game engine
3d game engine3d game engine
3d game engine
 
Hadoop meetup 2014
Hadoop meetup 2014Hadoop meetup 2014
Hadoop meetup 2014
 

Similar to 14multithreaded Graphics

I wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdfI wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdf
feelinggifts
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 
Pygame presentation
Pygame presentationPygame presentation
Pygame presentation
Felix Z. Hoffmann
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
Jussi Pohjolainen
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientBin Shao
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdf
ShaiAlmog1
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
DroidConTLV
 
Intro to computer vision in .net
Intro to computer vision in .netIntro to computer vision in .net
Intro to computer vision in .net
Stephen Lorello
 
The Ring programming language version 1.6 book - Part 73 of 189
The Ring programming language version 1.6 book - Part 73 of 189The Ring programming language version 1.6 book - Part 73 of 189
The Ring programming language version 1.6 book - Part 73 of 189
Mahmoud Samir Fayed
 
Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)
Korhan Bircan
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGL
gerbille
 
Computer graphics
Computer graphics Computer graphics
Computer graphics
shafiq sangi
 
Android Studio (Java)The SimplePaint app (full code given below).docx
Android Studio (Java)The SimplePaint app (full code given below).docxAndroid Studio (Java)The SimplePaint app (full code given below).docx
Android Studio (Java)The SimplePaint app (full code given below).docx
amrit47
 
Lhy tutorial gui(1)
Lhy tutorial gui(1)Lhy tutorial gui(1)
Lhy tutorial gui(1)
Brijesh Naik
 
Flash auto play image gallery
Flash auto play image galleryFlash auto play image gallery
Flash auto play image gallery
Boy Jeorge
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymore
Remy Sharp
 

Similar to 14multithreaded Graphics (20)

I wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdfI wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdf
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Real life XNA
Real life XNAReal life XNA
Real life XNA
 
Pygame presentation
Pygame presentationPygame presentation
Pygame presentation
 
GCD in Action
GCD in ActionGCD in Action
GCD in Action
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdf
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Of class1
Of class1Of class1
Of class1
 
Intro to computer vision in .net
Intro to computer vision in .netIntro to computer vision in .net
Intro to computer vision in .net
 
The Ring programming language version 1.6 book - Part 73 of 189
The Ring programming language version 1.6 book - Part 73 of 189The Ring programming language version 1.6 book - Part 73 of 189
The Ring programming language version 1.6 book - Part 73 of 189
 
Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGL
 
Computer graphics
Computer graphics Computer graphics
Computer graphics
 
Android Studio (Java)The SimplePaint app (full code given below).docx
Android Studio (Java)The SimplePaint app (full code given below).docxAndroid Studio (Java)The SimplePaint app (full code given below).docx
Android Studio (Java)The SimplePaint app (full code given below).docx
 
Tutorial flash
Tutorial flashTutorial flash
Tutorial flash
 
Lhy tutorial gui(1)
Lhy tutorial gui(1)Lhy tutorial gui(1)
Lhy tutorial gui(1)
 
Flash auto play image gallery
Flash auto play image galleryFlash auto play image gallery
Flash auto play image gallery
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymore
 

More from Adil Jafri

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5Adil Jafri
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net BibleAdil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming ClientsAdil Jafri
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran TochAdil Jafri
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10Adil Jafri
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx TutorialsAdil Jafri
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbAdil Jafri
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12Adil Jafri
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash TutorialAdil Jafri
 

More from Adil Jafri (20)

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
 
Php How To
Php How ToPhp How To
Php How To
 
Php How To
Php How ToPhp How To
Php How To
 
Owl Clock
Owl ClockOwl Clock
Owl Clock
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net Bible
 
Tcpip Intro
Tcpip IntroTcpip Intro
Tcpip Intro
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Jsp Tutorial
Jsp TutorialJsp Tutorial
Jsp Tutorial
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
 
Javascript
JavascriptJavascript
Javascript
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx Tutorials
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand Ejb
 
Html Css
Html CssHtml Css
Html Css
 
Digwc
DigwcDigwc
Digwc
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12
 
Html Frames
Html FramesHtml Frames
Html Frames
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
 

Recently uploaded

Sandra García Palero Fashion Portfolio..
Sandra García Palero Fashion Portfolio..Sandra García Palero Fashion Portfolio..
Sandra García Palero Fashion Portfolio..
SandraGarcaPalero
 
This is a certificate template for Daily Vacation Bible School Awards Can edi...
This is a certificate template for Daily Vacation Bible School Awards Can edi...This is a certificate template for Daily Vacation Bible School Awards Can edi...
This is a certificate template for Daily Vacation Bible School Awards Can edi...
RodilynColampit
 
HOW TO USE PINTEREST_by: Clarissa Credito
HOW TO USE PINTEREST_by: Clarissa CreditoHOW TO USE PINTEREST_by: Clarissa Credito
HOW TO USE PINTEREST_by: Clarissa Credito
ClarissaAlanoCredito
 
All the images mentioned in 'See What You're Missing'
All the images mentioned in 'See What You're Missing'All the images mentioned in 'See What You're Missing'
All the images mentioned in 'See What You're Missing'
Dave Boyle
 
Dino Ranch Storyboard / Kids TV Advertising
Dino Ranch Storyboard / Kids TV AdvertisingDino Ranch Storyboard / Kids TV Advertising
Dino Ranch Storyboard / Kids TV Advertising
Alessandro Occhipinti
 
Brushstrokes of Inspiration: Four Major Influences in Victor Gilbert’s Artist...
Brushstrokes of Inspiration: Four Major Influences in Victor Gilbert’s Artist...Brushstrokes of Inspiration: Four Major Influences in Victor Gilbert’s Artist...
Brushstrokes of Inspiration: Four Major Influences in Victor Gilbert’s Artist...
KendraJohnson54
 
Fashionista Chic Couture Mazes and Coloring AdventureA
Fashionista Chic Couture Mazes and Coloring AdventureAFashionista Chic Couture Mazes and Coloring AdventureA
Fashionista Chic Couture Mazes and Coloring AdventureA
julierjefferies8888
 
Complete Lab 123456789123456789123456789
Complete Lab 123456789123456789123456789Complete Lab 123456789123456789123456789
Complete Lab 123456789123456789123456789
vickyvikas51556
 
My storyboard for the short film "Maatla".
My storyboard for the short film "Maatla".My storyboard for the short film "Maatla".
My storyboard for the short film "Maatla".
AlejandroGuarnGutirr
 
ART APPRECIATION DISCUSSION LESSON 9.pptx
ART APPRECIATION DISCUSSION  LESSON 9.pptxART APPRECIATION DISCUSSION  LESSON 9.pptx
ART APPRECIATION DISCUSSION LESSON 9.pptx
AlizzaJoyceManuel
 
Domino Express Storyboard - TV Adv Toys 30"
Domino Express Storyboard - TV Adv Toys 30"Domino Express Storyboard - TV Adv Toys 30"
Domino Express Storyboard - TV Adv Toys 30"
Alessandro Occhipinti
 
Cherries 32 collection of colorful paintings
Cherries 32 collection of colorful paintingsCherries 32 collection of colorful paintings
Cherries 32 collection of colorful paintings
sandamichaela *
 
Heart Touching Romantic Love Shayari In English with Images
Heart Touching Romantic Love Shayari In English with ImagesHeart Touching Romantic Love Shayari In English with Images
Heart Touching Romantic Love Shayari In English with Images
Short Good Quotes
 
FinalA1LessonPlanMaking.docxdvdnlskdnvsldkvnsdkvn
FinalA1LessonPlanMaking.docxdvdnlskdnvsldkvnsdkvnFinalA1LessonPlanMaking.docxdvdnlskdnvsldkvnsdkvn
FinalA1LessonPlanMaking.docxdvdnlskdnvsldkvnsdkvn
abbieharman
 
Codes n Conventions Website Media studies.pptx
Codes n Conventions Website Media studies.pptxCodes n Conventions Website Media studies.pptx
Codes n Conventions Website Media studies.pptx
ZackSpencer3
 
FinalFinalSelf-PortraiturePowerPoint.pptx
FinalFinalSelf-PortraiturePowerPoint.pptxFinalFinalSelf-PortraiturePowerPoint.pptx
FinalFinalSelf-PortraiturePowerPoint.pptx
abbieharman
 
My storyboard for a sword fight scene with lightsabers
My storyboard for a sword fight scene with lightsabersMy storyboard for a sword fight scene with lightsabers
My storyboard for a sword fight scene with lightsabers
AlejandroGuarnGutirr
 
一比一原版(QUT毕业证)昆士兰科技大学毕业证成绩单如何办理
一比一原版(QUT毕业证)昆士兰科技大学毕业证成绩单如何办理一比一原版(QUT毕业证)昆士兰科技大学毕业证成绩单如何办理
一比一原版(QUT毕业证)昆士兰科技大学毕业证成绩单如何办理
zeyhe
 
A Brief Introduction About Hadj Ounis
A Brief  Introduction  About  Hadj OunisA Brief  Introduction  About  Hadj Ounis
A Brief Introduction About Hadj Ounis
Hadj Ounis
 
FinalLessonPlanResponding.docxnknknknknknk
FinalLessonPlanResponding.docxnknknknknknkFinalLessonPlanResponding.docxnknknknknknk
FinalLessonPlanResponding.docxnknknknknknk
abbieharman
 

Recently uploaded (20)

Sandra García Palero Fashion Portfolio..
Sandra García Palero Fashion Portfolio..Sandra García Palero Fashion Portfolio..
Sandra García Palero Fashion Portfolio..
 
This is a certificate template for Daily Vacation Bible School Awards Can edi...
This is a certificate template for Daily Vacation Bible School Awards Can edi...This is a certificate template for Daily Vacation Bible School Awards Can edi...
This is a certificate template for Daily Vacation Bible School Awards Can edi...
 
HOW TO USE PINTEREST_by: Clarissa Credito
HOW TO USE PINTEREST_by: Clarissa CreditoHOW TO USE PINTEREST_by: Clarissa Credito
HOW TO USE PINTEREST_by: Clarissa Credito
 
All the images mentioned in 'See What You're Missing'
All the images mentioned in 'See What You're Missing'All the images mentioned in 'See What You're Missing'
All the images mentioned in 'See What You're Missing'
 
Dino Ranch Storyboard / Kids TV Advertising
Dino Ranch Storyboard / Kids TV AdvertisingDino Ranch Storyboard / Kids TV Advertising
Dino Ranch Storyboard / Kids TV Advertising
 
Brushstrokes of Inspiration: Four Major Influences in Victor Gilbert’s Artist...
Brushstrokes of Inspiration: Four Major Influences in Victor Gilbert’s Artist...Brushstrokes of Inspiration: Four Major Influences in Victor Gilbert’s Artist...
Brushstrokes of Inspiration: Four Major Influences in Victor Gilbert’s Artist...
 
Fashionista Chic Couture Mazes and Coloring AdventureA
Fashionista Chic Couture Mazes and Coloring AdventureAFashionista Chic Couture Mazes and Coloring AdventureA
Fashionista Chic Couture Mazes and Coloring AdventureA
 
Complete Lab 123456789123456789123456789
Complete Lab 123456789123456789123456789Complete Lab 123456789123456789123456789
Complete Lab 123456789123456789123456789
 
My storyboard for the short film "Maatla".
My storyboard for the short film "Maatla".My storyboard for the short film "Maatla".
My storyboard for the short film "Maatla".
 
ART APPRECIATION DISCUSSION LESSON 9.pptx
ART APPRECIATION DISCUSSION  LESSON 9.pptxART APPRECIATION DISCUSSION  LESSON 9.pptx
ART APPRECIATION DISCUSSION LESSON 9.pptx
 
Domino Express Storyboard - TV Adv Toys 30"
Domino Express Storyboard - TV Adv Toys 30"Domino Express Storyboard - TV Adv Toys 30"
Domino Express Storyboard - TV Adv Toys 30"
 
Cherries 32 collection of colorful paintings
Cherries 32 collection of colorful paintingsCherries 32 collection of colorful paintings
Cherries 32 collection of colorful paintings
 
Heart Touching Romantic Love Shayari In English with Images
Heart Touching Romantic Love Shayari In English with ImagesHeart Touching Romantic Love Shayari In English with Images
Heart Touching Romantic Love Shayari In English with Images
 
FinalA1LessonPlanMaking.docxdvdnlskdnvsldkvnsdkvn
FinalA1LessonPlanMaking.docxdvdnlskdnvsldkvnsdkvnFinalA1LessonPlanMaking.docxdvdnlskdnvsldkvnsdkvn
FinalA1LessonPlanMaking.docxdvdnlskdnvsldkvnsdkvn
 
Codes n Conventions Website Media studies.pptx
Codes n Conventions Website Media studies.pptxCodes n Conventions Website Media studies.pptx
Codes n Conventions Website Media studies.pptx
 
FinalFinalSelf-PortraiturePowerPoint.pptx
FinalFinalSelf-PortraiturePowerPoint.pptxFinalFinalSelf-PortraiturePowerPoint.pptx
FinalFinalSelf-PortraiturePowerPoint.pptx
 
My storyboard for a sword fight scene with lightsabers
My storyboard for a sword fight scene with lightsabersMy storyboard for a sword fight scene with lightsabers
My storyboard for a sword fight scene with lightsabers
 
一比一原版(QUT毕业证)昆士兰科技大学毕业证成绩单如何办理
一比一原版(QUT毕业证)昆士兰科技大学毕业证成绩单如何办理一比一原版(QUT毕业证)昆士兰科技大学毕业证成绩单如何办理
一比一原版(QUT毕业证)昆士兰科技大学毕业证成绩单如何办理
 
A Brief Introduction About Hadj Ounis
A Brief  Introduction  About  Hadj OunisA Brief  Introduction  About  Hadj Ounis
A Brief Introduction About Hadj Ounis
 
FinalLessonPlanResponding.docxnknknknknknk
FinalLessonPlanResponding.docxnknknknknknkFinalLessonPlanResponding.docxnknknknknknk
FinalLessonPlanResponding.docxnknknknknknk
 

14multithreaded Graphics

  • 1. 1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Multithreaded Graphics
  • 2. Multithreaded Graphics2 www.corewebprogramming.com Agenda • Approaches for multithreaded graphics – Redraw everything in paint – Have routines other than paint draw directly on window – Override update and have paint do incremental updating – Double buffering • Reducing flicker in animations • Implementing double buffering • Animating images • Controlling timers
  • 3. Multithreaded Graphics3 www.corewebprogramming.com Multithreaded Graphics: Alternative Approaches • Redraw everything in paint – Simple and easy, but if things change quickly it is slow and can result in a flickering display • Have routines other than paint directly do drawing operations – Easy, efficient, and flicker-free, but results in “transient” drawing that is lost next time the screen is redrawn • Override update and have paint do incremental updating – Eliminates the flicker and improves efficiency somewhat, but requires the graphics to be non-overlapping • Double buffering – Most efficient option and has no problem with overlapping graphics. – More complex and requires additional memory resources
  • 4. Multithreaded Graphics4 www.corewebprogramming.com Redraw Everything in paint • Idea – Have user actions change non-graphical data structures, then call repaint. – The repaint method sets a flag that tells the event- handling process to call update. – The standard update method clears the screen and then calls paint. – The paint method completely redraws everything. • Advantage – Easy • Disadvantages – Flickers, slow.
  • 5. Multithreaded Graphics5 www.corewebprogramming.com Redrawing Everything in paint: Example import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.util.Vector; /** Applet that draws a small circle where you click. */ public class DrawCircles extends Applet { private Vector circles; public void init() { circles = new Vector(); addMouseListener(new CircleDrawer()); setBackground(Color.white); } ...
  • 6. Multithreaded Graphics6 www.corewebprogramming.com Redrawing Everything in paint: Example (Continued) /** When you click the mouse, create a SimpleCircle, * put it in the Vector, and tell the system * to repaint (which calls update, which clears * the screen and calls paint). */ private class CircleDrawer extends MouseAdapter { public void mousePressed(MouseEvent event) { circles.addElement(new SimpleCircle(event.getX(), event.getY(), 25)); repaint(); } }
  • 7. Multithreaded Graphics7 www.corewebprogramming.com Redrawing Everything in paint: Example (Continued) ... /** This loops down the available SimpleCircle * objects, drawing each one. */ public void paint(Graphics g) { SimpleCircle circle; for(int i=0; i<circles.size(); i++) { circle = (SimpleCircle)circles.elementAt(i); circle.draw(g); } } }
  • 8. Multithreaded Graphics8 www.corewebprogramming.com Redrawing Everything in paint: Example (Continued) public class SimpleCircle { private int x, y, radius; public SimpleCircle(int x, int y, int radius) { setX(x); setY(y); setRadius(radius); } /** Given a Graphics, draw the SimpleCircle * centered around its current position. */ public void draw(Graphics g) { g.fillOval(x - radius, y - radius, radius * 2, radius * 2); } ... }
  • 9. Multithreaded Graphics9 www.corewebprogramming.com Redrawing everything in paint: Result By storing results in a permanent data structure and redrawing the whole structure every time paint is invoked, you cause the drawing to persist even after the window is covered up and reexposed
  • 10. Multithreaded Graphics10 www.corewebprogramming.com Have Other Routines Draw Directly on Window • Idea – Arbitrary methods (i.e., other than paint) can call getGraphics to obtain the window’s Graphics object – Use that Graphics object to draw – Drawing lost if • Window covered up and reexposed • The update method called (e.g., via repaint) • Advantage – Fast • Disadvantage – Temporary
  • 11. Multithreaded Graphics11 www.corewebprogramming.com Drawing Directly on Window: Example public class Rubberband extends Applet { private int startX, startY, lastX, lastY; ... private void drawRectangle(Graphics g, int startX, int startY, int stopX, int stopY ) { int x, y, w, h; x = Math.min(startX, stopX); y = Math.min(startY, stopY); w = Math.abs(startX - stopX); h = Math.abs(startY - stopY); g.drawRect(x, y, w, h); } ... private class RectRecorder extends MouseAdapter { public void mousePressed(MouseEvent event) { startX = event.getX(); startY = event.getY(); lastX = startX; lastY = startY; }
  • 12. Multithreaded Graphics12 www.corewebprogramming.com Drawing Directly on Window: Example (Continued) public void mouseReleased(MouseEvent event) { Graphics g = getGraphics(); g.setXORMode(Color.lightGray); drawRectangle(g, startX, startY, lastX, lastY); } } private class RectDrawer extends MouseMotionAdapter { public void mouseDragged(MouseEvent event) { int x = event.getX(); int y = event.getY(); Graphics g = getGraphics(); g.setXORMode(Color.lightGray); drawRectangle(g, startX, startY, lastX, lastY); drawRectangle(g, startX, startY, x, y); lastX = x; lastY = y; } } }
  • 13. Multithreaded Graphics13 www.corewebprogramming.com Drawing Directly on Window: Result By retrieving the Graphics object, methods other than paint can draw directly on the window
  • 14. Multithreaded Graphics14 www.corewebprogramming.com Override update and Have paint do Incremental Updating • Idea – Have repaint (which triggers update) avoid clearing the screen each time by overriding update as follows: public void update(Graphics g) { paint(g); } – Then, assuming objects don’t overlap, erase each object at its old location by drawing over it in the background color then drawing it at the new location • Advantages – No flicker, faster • Disadvantage – Fails for overlapping images
  • 15. Multithreaded Graphics15 www.corewebprogramming.com Incremental Updating: Bounce Applet public class Bounce extends Applet implements Runnable, ActionListener { private Vector circles; private int width, height; private Button startButton, stopButton; private Thread animationThread = null; ... public void actionPerformed(ActionEvent event) { if (event.getSource() == startButton) { if (circles.size() == 0) { // Erase any circles from previous run. getGraphics().clearRect(0, 0, getSize().width, getSize().height); animationThread = new Thread(this); animationThread.start(); } int radius = 25; int x = radius + randomInt(width - 2 * radius); int y = radius + randomInt(height - 2 * radius); int deltaX = 1 + randomInt(10); int deltaY = 1 + randomInt(10); circles.addElement(new MovingCircle(x, y, radius, deltaX, deltaY));
  • 16. Multithreaded Graphics16 www.corewebprogramming.com Bounce Applet (Continued) } else if (event.getSource() == stopButton) { if (animationThread != null) { animationThread = null; // Stop animation circles.removeAllElements(); } } repaint(); } public void run() { Thread myThread = Thread.currentThread(); // Really while animationThread not null while(animationThread == myThread) { repaint(); pause(100); } } ...
  • 17. Multithreaded Graphics17 www.corewebprogramming.com Bounce Applet (Continued) public void update(Graphics g) { paint(g); } public void paint(Graphics g) { MovingCircle circle; for(int i=0; i<circles.size(); i++) { circle = (MovingCircle)circles.elementAt(i); g.setColor(getBackground()); circle.draw(g); // Old position circle.move(width, height); g.setColor(getForeground()); circle.draw(g); // New position } } ... }
  • 18. Multithreaded Graphics18 www.corewebprogramming.com Incremental Updating: MovingCircle Class public class MovingCircle extends SimpleCircle { private int deltaX, deltaY; ... public void move(int windowWidth, int windowHeight) { setX(getX() + getDeltaX()); setY(getY() + getDeltaY()); bounce(windowWidth, windowHeight); } private void bounce(int windowWidth, int windowHeight) { int x = getX(), y = getY(), radius = getRadius(), deltaX = getDeltaX(), deltaY = getDeltaY(); if ((x - radius < 0) && (deltaX < 0)) setDeltaX(-deltaX); else if ((x + radius > windowWidth) && (deltaX > 0)) setDeltaX(-deltaX); if ((y -radius < 0) && (deltaY < 0)) setDeltaY(-deltaY); else if((y + radius > windowHeight) && (deltaY > 0)) setDeltaY(-deltaY); } ... }
  • 19. Multithreaded Graphics19 www.corewebprogramming.com Incremental Updating, Result Incremental updating from paint can be flicker free and relatively fast, but it does not easily handle overlapping items
  • 20. Multithreaded Graphics20 www.corewebprogramming.com Option 4: Double Buffering • Idea – Draw into an off-screen pixmap, then draw that pixmap on window • Outline 1. Override update to simply call paint • This prevents the flicker that would normally occur each time update clears the screen before calling paint 2. Allocate an Image using createImage • Note that since this image uses native window-system support, it cannot be done until a window actually appears 3. Look up its Graphics object using getGraphics • Unlike with windows, where you need to look up the Graphics context each time you draw, with images it is reliable to look it up once, store it, and reuse the same reference thereafter 4. For each step, clear the image and redraw all objects onto it • Dramatically faster than drawing onto a visible window 5. Draw the offscreen image onto the window • Use drawImage
  • 21. Multithreaded Graphics21 www.corewebprogramming.com Double Buffering: Pros & Cons • Advantages – Much faster – Can easily handle overlapping objects • Disadvantages – More complex – Memory requirements for offscreen pixmap – Sometimes less incremental update of display
  • 22. Multithreaded Graphics22 www.corewebprogramming.com Double Buffering: Example public class DoubleBufferBounce extends Applet implements Runnable, ActionListener { private Vector circles; private int width, height; private Image offScreenImage; private Graphics offScreenGraphics; private Button startButton, stopButton; private Thread animationThread = null; public void init() { setBackground(Color.white); width = getSize().width; height = getSize().height; offScreenImage = createImage(width, height); offScreenGraphics = offScreenImage.getGraphics(); // Automatic in some systems, not in others. offScreenGraphics.setColor(Color.black); circles = new Vector(); ... }
  • 23. Multithreaded Graphics23 www.corewebprogramming.com Double Buffering: Example public void run() { MovingCircle circle; Thread myThread = Thread.currentThread(); // Really while animationThread not null. while(animationThread == myThread) { for(int j=0; j<circles.size(); j++) { circle = (MovingCircle)circles.elementAt(j); circle.move(width, height); } repaint(); pause(100); } } public void paint(Graphics g) { offScreenGraphics.clearRect(0, 0, width, height); MovingCircle circle; for(int i=0; i<circles.size(); i++) { circle = (MovingCircle)circles.elementAt(i); circle.draw(offScreenGraphics); } g.drawImage(offScreenImage, 0, 0, this); } }
  • 24. Multithreaded Graphics24 www.corewebprogramming.com Double Buffering: Result At the expense of memory and some complexity, double buffering allows fast, flicker-free updating of possibly overlapping images
  • 25. Multithreaded Graphics25 www.corewebprogramming.com Array-Based Animation • Idea – Load a sequence of images into an array – Start a thread to cycle through the images and draw to the graphics object • Each time the thread loops through the while loop, the array index is incremented and repaint (which triggers update) is called to update the images on the screen – Stop the animation by setting a flag • In an applet, end the animation from the applet’s stop method
  • 26. Multithreaded Graphics26 www.corewebprogramming.com Array-Based Animation: Example public class ImageAnimation extends Applet { private static final int NUMDUKES = 2; private Duke[] dukes; // Duke has array of images private int i; public void init() { dukes = new Duke[NUMDUKES]; setBackground(Color.white); } public void start() { int tumbleDirection; for (int i=0; i<NUMDUKES ; i++) { tumbleDirection = (i%2 == 0) ? 1 :-1; dukes[i] = new Duke(tumbleDirection, this); dukes[i].start(); } } ...
  • 27. Multithreaded Graphics27 www.corewebprogramming.com Animation Example (Continued) public void update(Graphics g) { paint(g); } public void paint(Graphics g) { for (i=0 ; i<NUMDUKES ; i++) { if (dukes[i] != null) { g.drawImage(Duke.images[dukes[i].getIndex()], 200*i, 0, this); } } } public void stop() { for (int i=0; i<NUMDUKES ; i++) { if (dukes[i] != null) { dukes[i].setState(Duke.STOP); } } } }
  • 28. Multithreaded Graphics28 www.corewebprogramming.com Animation Example (Continued) public class Duke extends Thread { ... public static Image[] images; private static final int NUMIMAGES = 15; private static Object lock = new Object(); private int state = RUN; public Duke(int tumbleDirection, Applet parent) { this.tumbleDirection = tumbleDirection; this.parent = parent; synchronized(lock) { if (images == null) { // If not previously loaded. images = new Image[ NUMIMAGES ]; for (int i=0; i<NUMIMAGES; i++) { images[i] = parent.getImage( parent.getCodeBase(), "images/T" + i + ".gif"); } } } } ...
  • 29. Multithreaded Graphics29 www.corewebprogramming.com Animation Example (Continued) public void run() { while (checkState()!=STOP) { index += tumbleDirection; if (index < 0) { index = NUMIMAGES - 1; } else if (index >= NUMIMAGES) { index = 0; } parent.repaint(); try { Thread.sleep(100); } catch (InterruptedException e) { break; // Break while loop. } } } }
  • 30. Multithreaded Graphics30 www.corewebprogramming.com Animation: Result Duke is a registered trademark of Sun Microsystems, Inc. All restrictions apply (http://www.sun.com/policies/trademarks/). Used with permission.
  • 31. Multithreaded Graphics31 www.corewebprogramming.com Timers • Swing defines a Timer class – A Timer can ring for a single cycle or fire periodically – At each ring an ActionEvent is fired – Useful for animations, simulations, and timing out secure network connections • Approach Timer timer = new Timer(milliseconds, listener); timer.start(); ... ... timer.stop();
  • 32. Multithreaded Graphics32 www.corewebprogramming.com Useful Timer Methods • start/stop – Starts or stops the timing sequence • restart – Cancels any undelivered time events and starts the timer again • setCoalesce – Turns coalescing off or on – By default, if a timer event is in the event queue (coalesce true), a new ActionEvent is not created at the next firing interval • setRepeats – Sets the timer to ring once (false) or to ring periodically (true) – Default behavior is to ring periodically
  • 33. Multithreaded Graphics33 www.corewebprogramming.com Timer: Example import java.awt.*; import javax.swing.*; public class TimedAnimation extends JApplet { private static final int NUMDUKES = 2; private TimedDuke[] dukes; private int i, index; public void init() { dukes = new TimedDuke[NUMDUKES]; setBackground(Color.white); dukes[0] = new TimedDuke( 1, 100, this); dukes[1] = new TimedDuke(-1, 500, this); } // Start each Duke timer. public void start() { for (int i=0; i<NUMDUKES ; i++) { dukes[i].start(); } } ...
  • 34. Multithreaded Graphics34 www.corewebprogramming.com Timer Example (Continued) ... public void paint(Graphics g) { for (i=0 ; i<NUMDUKES ; i++) { if (dukes[i] != null) { index = dukes[i].getIndex(); g.drawImage(TimedDuke.images[index], 200*i, 0, this); } } } // Stop each Duke timer. public void stop() { for (int i=0; i<NUMDUKES ; i++) { dukes[i].stop(); } } }
  • 35. Multithreaded Graphics35 www.corewebprogramming.com Timer Example (Continued) import java.applet.Applet; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TimedDuke extends Timer implements ActionListener { private static final int NUMIMAGES = 15; private static boolean loaded = false; private static Object lock = new Object(); private int tumbleDirection; private int index = 0; private Applet parent; public static Image[] images = new Image[NUMIMAGES]; public TimedDuke(int tumbleDirection, int msec, Applet parent) { super(msec, null); addActionListener(this); this.tumbleDirection = tumbleDirection; this.parent = parent; ...
  • 36. Multithreaded Graphics36 www.corewebprogramming.com Timer Example (Continued) synchronized (lock) { if (!loaded) { // Load images using MediaTracker ... } } } // Return current index into image array. public int getIndex() { return index; } // Receives timer firing event. Increments the index into // image array and forces repainting of the new image. public void actionPerformed(ActionEvent event) { index += tumbleDirection; if (index < 0){ index = NUMIMAGES - 1; } if (index >= NUMIMAGES) { index = 0; } parent.repaint(); } }
  • 37. Multithreaded Graphics37 www.corewebprogramming.com Timer Example: Result Each Duke moves at a different speed Duke is a registered trademark of Sun Microsystems, Inc. All restrictions apply (http://www.sun.com/policies/trademarks/). Used with permission.
  • 38. Multithreaded Graphics38 www.corewebprogramming.com Summary • Options – Redraw everything in paint – Have routines other than paint directly do drawing operations – Override update and have paint do incremental updating – Double buffering • Animation can be achieved by cycling through a sequence of images • Timers are restartable threads that fire an ActionEvent once or periodically
  • 39. 39 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Questions?