Java-如何制作计时器,以显示Jlabel中的时间



我现在正在编写我的第一个Java游戏的代码,到目前为止,我已经构建了GUI,我想添加一些逻辑。在我的游戏中,用户应该看到他的移动时间(以10秒开始),例如10、9、8、7、6、5、4、3、2、1、0。在它上面的时间。我的程序具有3个困难,首先是通过单击适当的JButton来选择一个,然后用户应查看计时器以及一些选择和播放的选项。我该如何解决这个问题?我在Java中阅读了有关计时器课程的信息,但仍然不知道如何在Jlabel上显示计算时间。也许我应该实施游戏循环,但是说实话,我不知道如何制作它。

您可以简单地使用计数计时器方法,然后将您的jlabel以及以下秒数和可选的"末期"消息传递给它。

Internet上有很多此类示例,但这是我快速演绎一个:

public static Timer CountdownTimer(JLabel comp, int secondsDuration, String... endOfTimeMessage) {                                         
    if (secondsDuration == 0) { return null; }
    String endMsg = "~nothing~";
    if (endOfTimeMessage.length>0) { endMsg = endOfTimeMessage[0]; }
    final String eMsg = endMsg;
    int seconds = secondsDuration;
    final long duration = seconds * 1000;
    JLabel label = (JLabel)comp;
    final Timer timer = new Timer(10, new ActionListener() {
        long startTime = -1;
        @Override
        public void actionPerformed(ActionEvent event) {
            if (startTime < 0) {
                startTime = System.currentTimeMillis();
            }
            long now = System.currentTimeMillis();
            long clockTime = now - startTime;
            if (clockTime >= duration) {
                ((Timer)event.getSource()).stop();
                if (!eMsg.equals("~nothing~")) { label.setText(eMsg); }
                return;
            }
            SimpleDateFormat df = new SimpleDateFormat("mm:ss:SSS");
            label.setText(df.format(duration - clockTime));
        }
    });
    timer.start(); 
    return timer;
}

如果要更改jlabel中计数的方式的方式,则可以更改 simpleDateFormat 字符串。此方法返回计时器对象,因此...您弄清楚如何在需要时停止它(在持续时间过期之前)。

最新更新