Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用java制作倒计时计时器_Java_Countdown - Fatal编程技术网

如何用java制作倒计时计时器

如何用java制作倒计时计时器,java,countdown,Java,Countdown,我是一名编程初学者(学生),被指派制作一个游戏。 我正在做的游戏叫博格尔。 在游戏中,玩家必须在给定的时间内在随机的字母板中找到单词。 但是我在创建计时器时遇到了麻烦。 这是我的计时器应该做的: 时间的动态输入(设置时间) 从输入时间倒计时到0 当o=>跳出循环时 我所需要知道的就是如何倒计时。 我不认为我需要ActionListener,因为它在类创建时就开始滴答作响 任何帮助、建议、链接、正确方向的推送都将被敞开双臂接受。您将看到人们使用Timer类来完成这项工作。不幸的是,它并不总

我是一名编程初学者(学生),被指派制作一个游戏。 我正在做的游戏叫博格尔。 在游戏中,玩家必须在给定的时间内在随机的字母板中找到单词。 但是我在创建计时器时遇到了麻烦。 这是我的计时器应该做的:


  • 时间的动态输入(设置时间)
  • 从输入时间倒计时到0
  • 当o=>跳出循环时
我所需要知道的就是如何倒计时。 我不认为我需要ActionListener,因为它在类创建时就开始滴答作响



任何帮助、建议、链接、正确方向的推送都将被敞开双臂接受。

您将看到人们使用Timer类来完成这项工作。不幸的是,它并不总是准确的。最好的方法是在用户输入输入时获取系统时间,计算目标系统时间,并检查系统时间是否超过目标系统时间。如果有,则打破循环

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;
}
}

试试这个。

您可以使用小程序创建倒计时计时器,下面是代码

   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 <param> tag inside the <applet> tag. Convert to ms.
    String minutes = getParameter("minutes");
    if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
    else remaining = 600000; // 10 minutes by default

    // Create a JLabel to display remaining time, and set some properties.
    label = new JLabel();
    label.setHorizontalAlignment(SwingConstants.CENTER );
    label.setOpaque(true); // So label draws the background color

    // Read some parameters for this JLabel object
    String font = getParameter("font");
    String foreground = getParameter("foreground");
    String background = getParameter("background");
    String imageURL = getParameter("image");

    // Set label properties based on those parameters
    if (font != null) label.setFont(Font.decode(font));
    if (foreground != null) label.setForeground(Color.decode(foreground));
    if (background != null) label.setBackground(Color.decode(background));
    if (imageURL != null) {
        // Load the image, and save it so we can release it later
        image = getImage(getDocumentBase(), imageURL);
        // Now display the image in the JLabel.
        label.setIcon(new ImageIcon(image));
    }

    // Now add the label to the applet. Like JFrame and JDialog, JApplet
    // has a content pane that you add children to
    getContentPane().add(label, BorderLayout.CENTER);

    // Get an optional AudioClip to play when the count expires
    String soundURL = getParameter("sound");
    if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);

    // Obtain a NumberFormat object to convert number of minutes and
    // seconds to strings. Set it up to produce a leading 0 if necessary
    format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(2); // pad with 0 if necessary

    // Specify a MouseListener to handle mouse events in the applet.
    // Note that the applet implements this interface itself
    addMouseListener(this);

    // Create a timer to call the actionPerformed() method immediately,
    // and then every 1000 milliseconds. Note we don't start the timer yet.
    timer = new Timer(1000, this);
    timer.setInitialDelay(0); // First timer is immediate.
}

// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }

// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates

// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates

// Return information about the applet
public String getAppletInfo() {
    return "Countdown applet Copyright (c) 2003 by David Flanagan";
}

// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }

// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
    {"minutes", "number", "time, in minutes, to countdown from"},
    {"font", "font", "optional font for the time display"},
    {"foreground", "color", "optional foreground color for the time"},
    {"background", "color", "optional background color"},
    {"image", "image URL", "optional image to display next to countdown"},
    {"sound", "sound URL", "optional sound to play when we reach 00:00"},
    {"newpage", "document URL", "URL to load when timer expires"},
};

// Start or resume the countdown
void resume() {
    // Restore the time we're counting down from and restart the timer.
    lastUpdate = System.currentTimeMillis();
    timer.start(); // Start the timer
}

// Pause the countdown
void pause() {
    // Subtract elapsed time from the remaining time and stop timing
    long now = System.currentTimeMillis();
    remaining -= (now - lastUpdate);
    timer.stop(); // Stop the timer
}

// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
    long now = System.currentTimeMillis(); // current time in ms
    long elapsed = now - lastUpdate; // ms elapsed since last update
    remaining -= elapsed; // adjust remaining time
    lastUpdate = now; // remember this update time

    // Convert remaining milliseconds to mm:ss format and display
    if (remaining < 0) remaining = 0;
    int minutes = (int)(remaining/60000);
    int seconds = (int)((remaining)/1000);
    label.setText(format.format(minutes) + ":" + format.format(seconds));

    // If we've completed the countdown beep and display new page
    if (remaining == 0) {
        // Stop updating now.
        timer.stop();
        // If we have an alarm sound clip, play it now.
        if (sound != null) sound.play();
        // If there is a newpage URL specified, make the browser
        // load that page now.
        String newpage = getParameter("newpage");
        if (newpage != null) {
            try {
                URL url = new URL(getDocumentBase(), newpage);
                getAppletContext().showDocument(url);
            }
            catch(MalformedURLException ex) {      showStatus(ex.toString()); }
        }
    }
}

// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }

// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
    pause(); // pause countdown
    showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
    resume(); // resume countdown
    showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
} 
import java.applet.*;
导入java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
导入javax.swing.Timer;//不是java.util.Timer
导入java.text.NumberFormat;
导入java.net。*;
/**
*从指定时间开始倒计时的小程序。到了零时,,
*它可以选择播放声音,也可以选择将浏览器移动到新页面。
*将鼠标放在小程序上暂停计数;将其移开以继续。
*这个类演示了大多数applet方法和特性。
**/
公共类倒计时扩展JApplet实现ActionListener、MouseListener
{
剩余时间长;//倒数还有多少毫秒。
long lastUpdate;//上次更新计数的时间
JLabel label;//显示计数
计时器;//每秒更新一次计数
NumberFormat format;//格式化分钟:秒和前导零
Image;//要随时间显示的图像
AudioClip声音;//到达00:00时播放的声音
//首次加载小程序时调用
公共void init(){
//通过读取“分钟”参数,计算出要计数多长时间
//在标记内的标记中定义。转换为ms。
字符串分钟数=getParameter(“分钟数”);
如果(分钟!=null)剩余=Integer.parseInt(分钟)*60000;
else剩余=600000;//默认为10分钟
//创建JLabel以显示剩余时间,并设置一些属性。
label=新的JLabel();
标签.设置水平对齐(SwingConstants.CENTER);
label.setOpaque(true);//因此label绘制背景色
//读取此JLabel对象的一些参数
字符串font=getParameter(“font”);
字符串前景=getParameter(“前景”);
字符串背景=getParameter(“背景”);
字符串imageURL=getParameter(“图像”);
//基于这些参数设置标签特性
if(font!=null)label.setFont(font.decode(font));
if(前台!=null)label.setForeground(Color.decode(前台));
if(background!=null)label.setBackground(Color.decode(background));
if(imageURL!=null){
//加载图像并保存,以便稍后发布
image=getImage(getDocumentBase(),imageURL);
//现在在JLabel中显示图像。
label.setIcon(新图像图标(图像));
}
//现在将标签添加到applet中,比如JFrame和JDialog,JApplet
//有一个可向其中添加子项的内容窗格
getContentPane().add(标签,BorderLayout.CENTER);
//获取一个可选的音频剪辑,以便在计数到期时播放
字符串soundURL=getParameter(“声音”);
如果(soundURL!=null)sound=getAudioClip(getDocumentBase(),soundURL);
//获取NumberFormat对象以转换分钟数和
//秒到字符串。如果需要,将其设置为产生前导0
format=NumberFormat.getNumberInstance();
format.setMinimumIntegerDigits(2);//如果需要,用0填充
//指定鼠标侦听器以处理小程序中的鼠标事件。
//请注意,小程序本身实现此接口
addMouseListener(这个);
//创建计时器以立即调用actionPerformed()方法,
//然后每1000毫秒。注意,我们还没有启动计时器。
定时器=新定时器(1000,此);
timer.setInitialDelay(0);//第一个计时器是立即的。
}
//释放我们持有的所有资源;小程序完成时调用
public void destroy(){if(image!=null)image.flush();}
//浏览器调用此命令以启动小程序运行
//resume()方法定义如下。
public void start(){resume();}//开始显示更新
//浏览器调用此命令以停止小程序。稍后可能会重新启动它。
//pause()方法定义如下
public void stop(){pause();}//停止显示更新
//返回有关小程序的信息
公共字符串getAppletInfo(){
返回“David Flanagan的倒数小程序版权(c)2003”;
}
//返回有关小程序参数的信息
公共字符串[][]getParameterInfo(){return parameterInfo;}
//这是参数信息。每个参数包含一个字符串数组
//参数。元素包括参数名称、类型和说明。
静态字符串[][]参数信息={
{“分钟”、“数字”、“时间,以分钟为单位,从“}”开始倒计时,
{“字体”、“字体”、“时间显示的可选字体”},
{“前景”、“颜色”、“当前可选前景颜色”},
{“背景”、“颜色”、“可选背景颜色”},
{“图像”、“图像URL”、“倒计时旁边显示的可选图像”},
{“声音”、“声音URL”、“到达00:00时播放的可选声音”},
{“新建页面”、“文档URL”、“计时器过期时加载的URL”},
};
//开始或恢复倒计时
作废简历(){
//恢复我们倒数计时的时间并重新启动计时器。
lastUpdate=System.currentTimeMillis();
timer.start();//Sta