CS2_38_Graphics2

CS2_38_Graphics2 - CS2 Module 38 Category: CS Concepts...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
CS2 Module 38 Category: CS Concepts Topic: Graphics 2 Objectives Simple Animation Bouncing ball Hypnotic Squares Paint/Repaint
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
CS 2 Introduction to Object Oriented Programming Module 38 CS Concepts Graphics 2
Background image of page 2
Basic Animation With successive, rapid repaintings, a Java component may appear to be animated. Other Java packages support more complex media; however, we can create our own simple animations by timing calls to repaint(). Techniques include: calling repaint() inside the paint() or paintComponent() methods. This schedules a prompt call to redraw the object. (Do NOT recursively call paint again.) creating a timer to call paint; can be useful to spawn execution threads to manage repainting (advanced topic not covered here.)
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Basic Animation Our algorithm for painting would include: 1) update the items being animated. (Stateful changes.) 2) erase the entire drawing area. (We might later refine this to only erase those areas that need updating.) 3) draw the updated items 4) repeat
Background image of page 4
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Bouncer extends JPanel implements ActionListener{ Timer timer; int ballX = 50, ballY = 50; int dx = 1, dy = 1; int diameter = 50; public void fire(){ timer = new Timer(5, this); timer.setCoalesce(true); // combine queued repaints timer.start(); } public void actionPerformed(ActionEvent e) { updateMovements(); checkCollisions(); repaint(); } public void updateMovements(){ ballY += dy; ballX += dx; }
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
public void checkCollisions(){ if (ballX + diameter > getSize().width || ballX < 0) dx*=-1; if (ballY + diameter > getSize().height || ballY < 0) dy *=-1; } public void paint(Graphics g){ g.setColor(Color.darkGray); g.fillRect(0,0, getSize().width, getSize().height); g.setColor(Color.red); g.fillOval(ballX, ballY, diameter, diameter); } To improve performance, investigate clipping areas: java.awt.Graphics.setClip(Rectangle);
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 20

CS2_38_Graphics2 - CS2 Module 38 Category: CS Concepts...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online