Do simple animation to show "work in progress"Tag(s): AWT
Like the previous How-to, using a Thread, we switch between 2 GIFs, for example ( and ).
Click the button to simulate some work,
click again to terminate the "work in progress"
[JDK1.1]
import java.applet.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; import java.net.*; public class AnimationProgress extends Applet implements ActionListener{ Image [] img; int index = 0; int maxImg; boolean working = false; Button b; MediaTracker tracker; public void init() { setLayout(new FlowLayout(FlowLayout.LEFT)); add(b = new Button("Working")); b.addActionListener(this); img = new Image[2]; // 2 images in animation maxImg = img.length - 1; tracker = new MediaTracker(this); try { // images loading img[0] = getImage(new URL(getDocumentBase(), "gumby.gif")); img[1] = getImage(new URL(getDocumentBase(), "gumby2.gif")); tracker.addImage(img[0],0); tracker.addImage(img[1],1); tracker.waitForAll(); } catch (Exception e) { e.printStackTrace(); } AnimationThread at = new AnimationThread(); at.delayedAnimation(this, 500); at.start(); } public void paint(Graphics g) { if (img[0] != null) { if (working) { g.drawImage(img[index],68,0,this); index = (index < maxImg) ? index + 1 : 0; } } } public void animate() { repaint(); } public void actionPerformed(ActionEvent ae) { working = !working; } class AnimationThread extends Thread { AnimationProgress animationApplet; int delay; public void delayedAnimation(AnimationProgress a, int delay) { this.animationApplet = a; this.delay = delay; } public void run() { while (true) { try { sleep(delay); animationApplet.animate(); } catch (Exception e) { e.printStackTrace(); } } } } }