How can I make a countdown in my applet?

此生再无相见时 提交于 2019-12-12 10:27:25

问题


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.

This is a Java Applet, not Javascript.

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?


回答1:


Use 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");
            }
        });
    }
}


来源:https://stackoverflow.com/questions/20354228/how-can-i-make-a-countdown-in-my-applet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!