|
CountDown
CountDown.java
/**
* CountDown.java
* Written By Chuck Cusack
* October, 2005
*
* A JPanel which displays a countdown.
* It uses a Thread so that the countdown can be delayed properly.
*
* Note: This is not the only way, and probably not the best way
* to accomplish this task, but it seems to work fine.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CountDown extends JPanel implements Runnable, ActionListener {
// ActionListener is implemented so that a button click (or whatever) can
// heard, and we can do our thing here.
// Runnable is implemented so we can create a Thread to execute the
// doIt method in such a way that we can create pauses.
private int currentNumber;
boolean working=false;
public void paintComponent(Graphics g) {
g.setColor(Color.black);
g.fillRect(0,0,200,200);
g.setColor(Color.red);
g.drawString(""+currentNumber,100,100);
}
// From the Runnable interface. When a thread is create with
// this Runnable object as a target, it executes this method.
// We use the variable "working" so that multiple button pushes
// will be ignored during animation.
public void run() {
working=true;
doIt(30);
working=false;
}
// When something invokes the actionPerformed method on this object,
// it will create a new Thread with this object as the target.
// Thus, when this method executes, the eventual result is that the
// run method executes. Of course, this depends on the value of
// the "working" variable.
public void actionPerformed(ActionEvent e) {
if(!working) {
new Thread(this).start();
}
}
// The recursive algorithm that does all the work.
// It prints the number n, pauses, and then makes a
// recursive call.
public void doIt(int n) {
// The base case
if(n<=0) return;
// Change the number and redraw
currentNumber=n;
repaint();
// Pause
try { Thread.sleep(500); }
catch (InterruptedException e){ }
// The recursive call
doIt(n-1);
}
}
|