Java计时器和actionlisteners

时间:2014-11-19 04:40:21

标签: java swing timer

Baiscilly,我正在为一个项目制作这个游戏,我无法确定如何让计时器工作,这是我的代码尝试。

import java.awt.event.*;
import java.util.Timer;

public class Timers {
    private int timeLeft = 60;
    private void timer() {
        while(timeLeft > 0){
             int delay = 1000;
              ActionListener taskPerformer = new ActionListener() {
                  public void actionPerformed(ActionEvent evt) {
                      timeLeft--;
                  }{
              new Timer(delay, taskPerformer).start();
              };
    };
}
}
}

我不知道我做错了什么或下一步做什么。除此之外,我还需要Actionlistener 查看用户的回答是否与预设答案相同。

import javax.swing.*;

import java.awt.event.*;

...

    JTextField Janswer = new JTextField();
    Janswer.setBounds(110, 70, 150, 25);
    newFrame.add(Janswer);
    if Janswer = equations.getanswer(){
        score++;

我想如果我付出这么多,我也可以给你从哪里得到答案

public class Equations {
    private static String equation;
    private int answer;
    Problems problem = new Problems();

    public Equations() {
        equation = problem.getFirstNumber() + " " + problem.getSign() + " " + problem.getSecondNumber();
        String sign = problem.getSign();
        if (sign.equals("+"))
            answer = problem.getFirstNumber() + problem.getSecondNumber();
        else if (sign.equals("-"))
            answer = problem.getFirstNumber() - problem.getSecondNumber();
        else if (sign.equals("*"))
            answer = problem.getFirstNumber() * problem.getSecondNumber();
    }

    public static String getEquations() {
        return equation;
    }
    public int getAnswer() {
        return answer;
    }
}

感谢大家给予我任何帮助,如果我需要以任何方式更改我的帖子,请告诉我,我是新手!

1 个答案:

答案 0 :(得分:1)

主要问题是你使用的是while-loop,它在每次迭代时都会创建一堆新的Timer,这些都会递减timeLeft值。您只需要一个Timer

根据你想做的事情,你可以做点像......

ActionListener taskPerformer = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        System.out.println("Time's up!");
    }
};
new Timer(60 * 1000, taskPerformer).start();

这将在1分钟内建立回调,这可以让您定义超时...

知道,如果你想要一个倒数计时器,你可以做点像......

ActionListener taskPerformer = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        count++;
        if (count >= 59) {
            ((Timer)evt.getSource()).stop();
            System.out.println("Time's up!");
        }
    }
};
new Timer(1000, taskPerformer).start();

基本上计为60(从0开始)并且每秒更新一次(您必须使用60 - count来获取倒计时值)...

有关详细信息,请参阅How to use Swing Timers