import java.util.Scanner; import java.util.Timer; import java.util.TimerTask; public class Stopwatch { static int interval; static Timer timer; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Input seconds => : "); String secs = sc.nextLine(); int delay = 1000; int period = 1000; timer = new Timer(); interval = Integer.parseInt(secs); System.out.println(secs); timer.scheduleAtFixedRate(new TimerTask() { public void run() { System.out.println(setInterval()); } }, delay, period); } private static final int setInterval() { if (interval == 1) timer.cancel(); return --interval; } }
尝试这个。
您可以使用applet创建倒数计时器,下面是代码,
import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.Timer; // not java.util.Timer import java.text.NumberFormat; import java.net.*; /** * An applet that counts down from a specified time. When it reaches 00:00, * it optionally plays a sound and optionally moves the browser to a new page. * Place the mouse over the applet to pause the count; move it off to resume. * This class demonstrates most applet methods and features. **/ public class Countdown extends JApplet implements ActionListener, MouseListener { long remaining; // How many milliseconds remain in the countdown. long lastUpdate; // When count was last updated JLabel label; // Displays the count Timer timer; // Updates the count every second NumberFormat format; // Format minutes:seconds with leading zeros Image image; // Image to display along with the time AudioClip sound; // Sound to play when we reach 00:00 // Called when the applet is first loaded public void init() { // Figure out how long to count for by reading the "minutes" parameter // defined in a tag inside the