我怎样才能让我的小程序倒计时? [英] How can I make a countdown in my applet?

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

问题描述

我在写一个游戏,需要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小程序,JavaScript不。

This is a Java Applet, not Javascript.

有没有一种方法,而我使用的其他按钮我可以在这个背景去计时器?我使用的JLabel和Jbutton中。我可以在同一时间运行两个的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中的

运行这个例子。你会看到,时间已经不多,而你仍然可以执行其他操作。单击Yes或No按钮,而时间会

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天全站免登陆