如何在我的小程序中进行倒计时? [英] How can I make a countdown in my applet?

查看:23
本文介绍了如何在我的小程序中进行倒计时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写游戏,需要 60 秒倒计时.当我点击开始"按钮时,我希望它开始倒计时.我现在可以手动让它倒计时,但需要它自动倒计时.

I'm writing a game and need a 60 second countdown. I would like it to start counting down when I click the "Start" button. I can get it to countdown manually right now, but need it to do so automatically.

这是一个 Java Applet,而不是 Javascript.

This is a Java Applet, not Javascript.

当我使用其他按钮时,有没有办法让这个计时器在后台运行?我正在使用 JLabels 和 JButtons.我可以同时运行两个 ActionListeners 吗?

Is there a way I can have this timer go in the background while I use other buttons? I'm using JLabels and JButtons. Can I have two ActionListeners running at the same time?

推荐答案

使用 javax.swing.Timer

运行这个例子.您将看到在时间运行期间您仍然可以执行其他操作.时间到了,点击是或否按钮

Run this example. You will see that you can still perform other actions while the time is running. Click the yes or no button, while the time is going

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Test extends JApplet {

    private JLabel label1 = new JLabel("60");
    private JLabel label2 = new JLabel("Yes");
    private JButton jbt1 = new JButton("Yes");
    private JButton jbt2 = new JButton("No");
    private int count = 60;
    private Timer timer;

    public Test() {
        JPanel panel1 = new JPanel(new GridLayout(1, 2));
        panel1.add(label1);
        panel1.add(label2);
        label1.setHorizontalAlignment(JLabel.CENTER);
        label2.setHorizontalAlignment(JLabel.CENTER);
        JPanel panel2 = new JPanel();
        panel2.add(jbt1);
        panel2.add(jbt2);

        add(panel1, BorderLayout.CENTER);
        add(panel2, BorderLayout.SOUTH);

        timer = new Timer(1000, new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                count--;
                if (count == 0) timer.stop();

                label1.setText(String.valueOf(count));

            }
        });
        timer.start();

        jbt1.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                label2.setText("Yes");
            }
        });
        jbt2.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                label2.setText("No");
            }
        });
    }
}

这篇关于如何在我的小程序中进行倒计时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆