Recitation 12 November 18, 2011
Today’s Goals: Use Threads to animate changes.
Creating a thread } Creates a new Command Creates a new Java thread public void animateFromOrigin() { Runnable animateCommand = new AnimationCommand(…); Thread thread = new Thread(animateCommand); thread.setName(“Shuttle Animation”); thread.start(); } Invokes the run method on the command object passed to constructor.
Pausing a thread void sleep(int pauseTime) { try { // OS suspends program for pauseTime Thread.sleep(pauseTime); } catch (Exception e) { // program may be forcibly interrupted while sleeping e.printStackTrace(); }; }
java.lang.Runnable Interface Command Object run () package java.lang; public interface Runnable { public void run(); }
Runnable Implementation public class AShuttleAnimationCommand implements Runnable{ Shuttle shuttle; int animationStep, animationPauseTime; public AShuttleAnimationCommand (Shuttle shuttle, int step, int pause) { this.shuttle = shuttle; animationStep = step; animationPauseTime = pause; } public void run() { shuttle.animateFromOrigin(animationStep,animationPauseTime); Note: Will likely need to specify additional parameters (e.g. where to move to!) Parameters Target Object
Recitation Specification Goal: Animate the changes to a Triangle’s x and y position. Tasks: Implement animateSetX/Y methods in CartesianLine.java Implement run() in both ASetXCommand and ASetYCommand Bonus: Animate push and pop onto shape stack, using code from Recitation 11
Setup and Submission Work with a single partner! Please follow the instructions on the course website to set up and submit your projects! Set up your project: http://www.cs.unc.edu/~dewan/comp114/f10/Recitations/makeproject/ Submit an assignment: http://www.cs.unc.edu/~dewan/comp114/f10/Recitations/submit/ Work with a single partner!