Jim Priest, Peter Lundgren, Russell Bennett
Background info A sequence of fames You have some experience already Used for some GUI’s and Games
Example /** * Draws the World and its Balls. * g the Graphics object onto which to draw. 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. }
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.
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
Important Concepts “Flashing” Overriding the update() method Off-screen images “Double buffering”
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); }
Questions? Next, Demo