Download presentation
Presentation is loading. Please wait.
1
Jim Priest, Peter Lundgren, Russell Bennett
2
Background info A sequence of fames You have some experience already Used for some GUI’s and Games
3
Example /** * Draws the World and its Balls. * * @param g the Graphics object onto which to draw. */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D graphics = (Graphics2D) g; this.drawWorld(graphics); this.drawBalls(graphics); } /** * Repeatedly repaints this panel. */ public void run() { while (true) { try { Thread.sleep(this.timeToSleep); this.repaint(); } catch (InterruptedException exception) { // If you can't sleep, no problem -- just continue. }
4
Important Concepts Using threads to control animation behavior Controlling the speed and smoothness using.sleep() Have a frame rate field. Pass 1000/frameRate to.sleep() Can’t have different frame rates for different animation objects on screen at same time After sleep, calls repaint.
5
Important Concepts Using the run method Contains the animation thread Can be used to draw on the Frame Using the paintComponent method Can be used to draw on the frame Still needs a thread to handle updating the frame
6
Important Concepts “Flashing” Overriding the update() method Off-screen images “Double buffering”
7
Example class OptimizedDoubleBufferedCanvas extends Canvas { public void update(Graphics g) { Graphics offgc; Image offscreen = null; Rectangle box = g.getClipRect(); // create the offscreen buffer and associated Graphics offscreen = createImage(box.width, box.height); offgc = offscreen.getGraphics(); // clear the exposed area offgc.setColor(getBackground()); offgc.fillRect(0, 0, box.width, box.height); offgc.setColor(getForeground()); // do normal redraw offgc.translate(-box.x, -box.y); paint(offgc); // transfer offscreen to window g.drawImage(offscreen, box.x, box.y, this); }
8
Questions? Next, Demo
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.