This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Stop timer with conditional only works first time?
I'm very confused as to how to make a timer using the swing and not util timer.
I am making a game where users have to answer questions in a 30 second time limit. I have a PlayFrame, where the time is shown, and a method inside PlayFrame called startTimer which contains all the timer stuff.
public static void startTimer() {
int elapsedSeconds = 0;
javax.swing.Timer myTimer = new javax.swing.Timer(1000, new MyTimerActionListener());
elapsedSeconds++;
if (elapsedSeconds == 30) {
myTimer.stop();
timerLabel.setText("0");
wrong();
} else {
String text = String.format("f", 30 - elapsedSeconds);
timerLabel.setText(text);
}
if (myTimer != null && myTimer.isRunning()) {
myTimer.stop();
myTimer = null;
timerLabel.setText("0");
} else {
elapsedSeconds = 0;
myTimer = new javax.swing.Timer(1000, new MyTimerActionListener());
myTimer.start();
String text = String.format("t", 30);
timerLabel.setText(text);
}
}
What I want this method to do is have a timer that counts down from 30 until the question is answered correctly. If the answer is answered incorrectly I want the timer to stop.
For an answer perhaps some psuedocode (or real code) to move me in the right direction. And this is for personal use, not homework or anything.
Please remember that this is a part of my whole code and it needs to work with other parts of it. I'll give more information upon request, thanks!
EDIT: New startTimer() method NOTE all System.out.print is for testing only:
public static void startTimer() {
class TimerListener implements ActionListener {
Timer timer = new Timer(1000, new TimerListener());
int elapsedSeconds = 30;
String seconds = Integer.toString(elapsedSeconds);
#Override
public void actionPerformed(ActionEvent evt) {
timer.start();
if (elapsedSeconds == 0) {
//System.out.print("here");
timer.stop();
PlayFrame.wrong();
}
else{
//System.out.print("hersfde");
elapsedSeconds--;
PlayFrame.timerLabel.setText(seconds);
}
//System.out.println(elapsedSeconds);
}
}
//System.out.print("l");
}
Doesn't do anything and not sure why.
This is how I would make a countdown timer:
Timer timer = new Timer(1000, new TimerListener());
class TimerListener implements ActionListener{
int elapsedSeconds = 30;
public void actionPerformed(ActionEvent evt){
elapsedSeconds--;
timerLabel.setText(elapsedSeconds)
if(elapsedSeconds <= 0){
timer.stop();
wrong()
// fill'er up here...
}
}
}
Related
I'm creating a game that ends if you haven't reached a certain point by the time the timer reaches zero. It currently works and I can create multiple TimerTasks at one time, but I cannot cancel them. Currently, clicking the button resets the timer (on the display) but will still run in the background and end the program when it reaches zero (even though it shouldn't be running). Here's the code for the ActionListener that starts each timer.
public class Game implements Runnable {
private int currentScore, difficulty, level, highscore, x, y;
private boolean playMusic, playClicks, gameRunning;
private boolean stopLastTimer = false;
JFrame gameFrame;
Data data;
JButton target;
Thread t;
JLabel score;
Timer globalTimer = new Timer();
JLabel timer;
ActionListener clickedAction = new ActionListener(){
public void actionPerformed(ActionEvent ae) {
stopLastTimer = true;
t.interrupt();
currentScore++;
score.setText("Score: " + currentScore);
//playClickSound();
globalTimer.schedule(new TimerTask(){
double second = 2.0;
#Override
public void run() {
second = second - 0.1;
if(stopLastTimer) {
this.cancel(); stopLastTimer = false; } //should end old timer here
if(second == 0.0) {
this.cancel();
gameStop();
}
second = limitPrecision(Double.toString(second), 1);
timer.setText(second + "s");
}
},0, 100);
}
};
Don't use a TimerTask.
Instead you should be using a javax.swing.Timer for the animation. A Swing Timer has a stop() method.
The source of the ActionEvent will be the Timer itself.
Read the section from the Swing tutorial on How to Use Timer for more information and working examples.
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 Timers 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
I have 6 objects in the class GUI which are moving through the code:
Anim anim = new Anim();
Timer timer = new Timer();
timer.scheduleAtFixedRate(anim, 30, 30);
When an object comes to a point I want to stop it. In class Anim I'm doing:
public class Anim extends TimerTask {
#Override
public void run() {
if (t1.x == 300 && t1.y == 300) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It stops application, and I want have stayed at a concrete object. How to do it?
EDIT:
Ok, now it works well, does not interfere with other objects. But the object is moving on and after 1 second back to the starting position. I wish the whole time he was in the same position when a sleep.
if (Main.auto1.x == 700 && Main.auto1.y == 350) {
timer = new javax.swing.Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Main.auto1.x = 700;
Main.auto1.y = 350;
}
});
timer.setRepeats(false);
timer.start();
Use Swing Timer instead of Thread.sleep() and Java Timer in a Swing application that sometime hangs the Swing applicaion.
Read more How to Use Swing Timers
Sample code:
private Timer timer;
...
timer = new javax.swing.Timer(3000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//do what ever you want to do
// call timer.stop() when the condition is matched
}
});
timer.setRepeats(true);
timer.start();
EDIT
Please have a look at my another post How to fix animation lags in Java?
I have problem referencing the Timer to the ActionListener class. I want to stop the timer after Java displays the dialog box that displays the time and starts again after clicking on "Yes".
This is what I currently have:
public class AlarmClock
{
public static void main(String[] args)
{
boolean status = true;
Timer t = null;
ActionListener listener = new TimePrinter(t);
t = new Timer(10000, listener);
t.start();
while(status)
{
}
}
}
class TimePrinter implements ActionListener
{
Timer t;
public TimePrinter(Timer t)
{
this.t = t;
}
public void actionPerformed(ActionEvent event)
{
t.stop(); //To stop the timer after it displays the time
Date now = Calendar.getInstance().getTime();
DateFormat time = new SimpleDateFormat("HH:mm:ss.");
Toolkit.getDefaultToolkit().beep();
int choice = JOptionPane.showConfirmDialog(null, "The time now is "+time.format(now)+"\nSnooze?", "Alarm Clock", JOptionPane.YES_NO_OPTION);
if(choice == JOptionPane.NO_OPTION)
{
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null, "Snooze activated.");
t.start(); //To start the timer again
}
}
}
However, this code gives a null pointer exception error. Is there any other way I can reference the Timer?
You have a chicken-and-egg problem here, since the constructors of both classes require a reference to each other. You need to break the cycle somehow, the easiest way would be to construct the Timer without a listener, then construct the listener, then add it to the timer:
t = new Timer(10000, null);
ActionListener l = new TimePrinter(t);
t.addActionListener(l);
Alternatively, you could add a setter to TimePrinter instead of passing the Timer to its constructor:
class TimePrinter implements ActionListener
{
Timer t;
public TimePrinter() {}
public setTimer(Timer t)
{
this.t = t;
}
and then do
TimePrinter listener = new TimePrinter();
t = new Timer(10000, listener);
listener.setTimer(t);
Either way the end result is the same.
I am making a simple target shooting game.I have a countdownTimer inside the label and an object that blinks in a random position inside the panel. Every time I click on the object,. the object's timer stops which makes that object stop too, but the countdown timer doesn't and that is my problem. I want the countdown timer should stop also.
Could someone help me about this matter?
Here's the code :
private void starting()
{
new Timer(TIMER_PERIOD, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if (count++ < MAX_COUNT)
{
String text = "Time remaining: (" + (MAX_COUNT - count) + ") seconds left";
setCountDownLabelText(text);
Date date = new Date();
setCountDownPanelText(date);
}
else
{
((Timer) e.getSource()).stop();
randomTimer.stop();
JOptionPane.showMessageDialog(null, "Game Over");
System.exit(0);
}
}
}).start();
}
It strikes me that you don't understand the code at all, that you are unaware of the anonymous class created that is extending Timer, which (if you'd seen the documentation) has a function stop() which does what you ask.
You need to store a reference to the Timer.
private javax.swing.Timer timer;
private void starting() {
timer = new Timer(TIMER_PERIOD, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
// do stuff
// stop the timer
timer.stop();
// do other stuff
}
}
}