Java Animation Chris North cs 3724 HCI Animation















- Slides: 15
Java: Animation Chris North cs 3724: HCI
Animation? • Changing graphics over time • Examples: • • cartoons Clippy, agents/assistants Hour glass Save dohicky Progress bar Copy file Amit’s pulsating plot
Purvi • Algorithm Animation
Java Graphics Review • Extend JPanel • Override paint. Component( ) method public class My. Panel extends JPanel { public void paint. Component(Graphics g){ super. paint. Component(g); Graphics 2 D g 2 = (Graphics 2 D)g; // my graphics here: g 2. draw. String("Hello World", 10); } }
Ticker
Animating the ticker text • Keep repainting graphics using different x public class My. Panel extends JPanel { int x; public void paint. Component(Graphics g){ super. paint. Component(g); Graphics 2 D g 2 = (Graphics 2 D)g; // my graphics here: g 2. draw. String("Hello World", x, 10); } }
Animation Loop • Update x location (member variable) • Repaint While(true){ //infinite loop x = x – 1; repaint(); //calls paint. Component() Thread. sleep(10); //slow down animation } • Problem?
Multi-Threading • Loop prevents other parts of code from executing • User events pile up • Multiple threads let multiple methods execute simultaneously (multi-tasking) • Threads = lightweight processes, shared memory Main thread Anim thread User interaction Update graphics
Java Threads • implement Runnable interface • Override run( ) method • Put animation loop here • new Thread(runnable) • Thread. start( ) • Calls runnable. run( ) in new thread Runnable run( ) My Panel Thread start( )
Simplifying • My. Panel implements Runnable run( ) My Panel Runnable Thread start( ) run( ) Thread start( )
Threaded Ticker public class My. Panel extends JPanel implements Runnable { int x = 100; Thread mythread; public My. Panel(){ // constructor mythread = new Thread(this); mythread. start(); } public void run(){ while(true){ // animation loop or in button code that starts animation x = x – 5; repaint(); Thread. sleep(100); } } public void paint. Component(Graphics g){ super. paint. Component(g); Graphics 2 D g 2 = (Graphics 2 D)g; g 2. draw. String("Hello World", x, 10); } } // my graphics
Stopping a Thread • Stop animation loop with a flag • mythread = null; will cleanup thread object Boolean run. My. Animation; While(run. My. Animation){ //flag stops loop x = x – 5; repaint(); //calls paint. Component() Thread. sleep(100); //slow down animation }
Controlling Animation Speed While(true){ x = x – 5; repaint(); Thread. sleep(100); } //animation step size //delay between steps Milliseconds 1000 = 1 second
Animation Summary • In a secondary thread: 1. 2. 3. 4. Make changes to global state Repaint Sleep delay Repeat • Use double buffering as needed
JBuilder Example