Baiscilly, I'm making this game for a project, and I can't fiure out how to get timers to work whatsoever, here is my code attempting.
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();
};
};
}
}
}
I don't know what I'm doing wrong or what to do next. As well as this i need to make an Actionlistener
see if the users answer is the same as the preset answer.
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++;
And I guess if i'm giving this much I may as well give you where it is getting the answers from
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;
}
}
Thank you all for any help you're able to give me, and just let me know if I need to change my post in any way, I'm new to this!
The main problem is you are using a while-loop
, which is creating a bunch of new Timer
s on each iteration, which are all decrementing the timeLeft
value. You only need a single Timer
.
Depending on what you want to do, you could do something like...
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Time's up!");
}
};
new Timer(60 * 1000, taskPerformer).start();
This will establish a call back in 1 minutes time, which can allow you to define a timeout...
Know, if you want a count down timer, you could do something like...
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();
Which basically counts to 60 (from 0) and is updated every second (you'd have to use 60 - count
to get the count down value)...
See How to use Swing Timers for more details
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.