2

I'm using the swing Timer to make a countdown clock in Netbeans:

public void startTimer() {

    System.out.println(right + "value");
    ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            System.out.println("action");
            timerLabel.setText("" + seconds);
            --seconds;
            System.out.println(seconds);
            if (seconds == -1 && seconds < 0) {
                System.out.print("zero");
                //displayTimer.stop();
                wrong();
                dispose();
            }
        }
    };
    displayTimer = new Timer(1000, listener);
    displayTimer.setInitialDelay(100);
    displayTimer.start();

    if (right == null) {
        System.out.println("null");
    } else if (right == true) {
        System.out.println("truehere");
        displayTimer.stop();
        right = null;
        seconds = 20;
        displayTimer.setDelay(10000);
        displayTimer.setInitialDelay(100);
        displayTimer.start();
    } else if (right == false) {
        System.out.print("wrong");
        //displayTimer.stop();
        seconds = 20;
    }


}

I just use System.out.print to test the program, it's not a part of the real program. I call the stop() method but the timer continues to count. Also, I create a new timer by displayTimer = new javax.swing.Timer(10000, listener); but it counts twice as fast. Can anyone help?

EDIT:

Here is my timer (sort of SSCCE):

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;

import javax.swing.*;

public class JavaApplication8 {
 public static void startTimer() {
    ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            int seconds = 20;
            seconds--;
            System.out.println(seconds);

            if (seconds == -1 && seconds < 0) {
                System.out.print("zero");
            }
        }
    };
    Timer displayTimer = new Timer(1000, listener);
    displayTimer.setInitialDelay(100);
    displayTimer.start();
 }

public static void main(String[] args) {
    System.out.println("Type win to win!");

    startTimer();

    String read;
    Boolean right;
    int seconds;

    Scanner scanIn = new Scanner(System.in);
    read = scanIn.nextLine();

    if (read.equals("win")){
        right = true;
    }
    else{
        right = false;
    }

    if (right == true) {
        System.out.println("correct");
        //displayTimer.stop();
        right = null;
        seconds = 20;
        //displayTimer.setDelay(10000);
        //displayTimer.setInitialDelay(100);
        //displayTimer.start();
    } else if (right == false) {
        System.out.print("incorrect");
        //displayTimer.stop();
        seconds = 20;
        right = null;
    }
}
}

it doesn't work right in that the seconds don't show up, but it does show 20 times which is what I want. This is just in its own application, in my real program it is easier to see the problem.

I've noticed that the first time the game runs it works fine. Then I click play again (resets the whole game) and it goes twice as fast. Maybe I'm not resetting something correctly? Here is my reset code:

// Reset Everything
    PlayFrame.seconds = 20;
    PlayFrame.winnings = 0;
    PlayFrame.right = false;
    //PlayFrame.displayTimer.stop();
    PlayFrame.questionLabel.setText(null);
    PlayFrame.count = 0;
    WelcomeFrame WFrame = new WelcomeFrame();
    WFrame.setVisible(true);
    setVisible(false);                             
    PlayFrame P = new PlayFrame();
    P.dispose();

    if (PlayFrame.seconds == -1 && PlayFrame.seconds < 0){
        PlayFrame.displayTimer.stop();
    }
}
CodeAddict
  • 194
  • 2
  • 5
  • 19
  • 1
    Consider posting an [sscce](http://sscce.org). – Hovercraft Full Of Eels Jan 19 '13 at 00:39
  • Try removing this line `displayTimer.removeActionListener(listener);` This doesnt make any sense and use only one instance of timer for all your activities. – Smit Jan 19 '13 at 00:51
  • @HovercraftFullOfEels I can't, I've been trying but I can't – CodeAddict Jan 19 '13 at 00:56
  • @CodeAddict I have one pseudo code. but I am not sure will that help you or not. – Smit Jan 19 '13 at 01:05
  • What is the variable `right` supposed to do? – APerson Jan 19 '13 at 01:09
  • @APerson241 right is a boolean, its initially false and if the user gets the question right it is set to true. If they get it wrong it is set to null – CodeAddict Jan 19 '13 at 01:16
  • @smit it might help, anything would help at this point – CodeAddict Jan 19 '13 at 01:16
  • @CodeAddict I put it as answer. I hope this helps. Moreover `right` is boolean so you dont need to use `==`. You are checking for either true or false then dont use `else if (right == null) {` (doest make any sense) just `else` will work. – Smit Jan 19 '13 at 01:25
  • @smit I thought in conditionals you needed double `==` and it is false to begin with, and null if wrong. thats not the issue – CodeAddict Jan 19 '13 at 01:28
  • @CodeAddict for boolean you don't need `==`. `right could be either true or false`. So I mean if you equate or not result will be same. What I mean is `if(right==true)` is nothing but `if(right)` considering `right = true` However primitive types cant be null. See here [Can an int be null in Java?](http://stackoverflow.com/questions/2254435/can-an-int-be-null-in-java) – Smit Jan 19 '13 at 01:34
  • Okay, thanks. But that's not the issue im having. It's with the multiple timers – CodeAddict Jan 19 '13 at 01:37
  • @CodeAddict You don't need multiple timer. You just need one timer and start and stop that timer according to your need. Like the way I showed in my pseudo code. – Smit Jan 19 '13 at 01:38
  • Please post your full code/SSCCE – joey rohan Jan 19 '13 at 10:36
  • @joeyrohan I really can't post an sscce, i've tried but I can't get it to work. And the rest of my code is just showing text in labels and moving between frames – CodeAddict Jan 19 '13 at 14:44
  • @CodeAddict don't think about the working, just paste what ever you have done :) – joey rohan Jan 19 '13 at 16:42
  • alright everyone, question is updated with new code and a (sort of) sscce – CodeAddict Jan 19 '13 at 16:57
  • Possible duplicate of [How to Stop Javax.Swing.timer?](http://stackoverflow.com/questions/21252960/how-to-stop-javax-swing-timer) – Samuel Owino Feb 01 '17 at 23:46

1 Answers1

3

Its just pseudo code to see how timer can be started and stopped.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.Timer;

public class TimerOnJLabel extends JFrame {

    private static final long serialVersionUID = 1L;        
    long start = System.currentTimeMillis();
    long elapsedTimeMillis;
    int sec = 5;
    Timer timer;

    public TimerOnJLabel() {
        super("TooltipInSwing");
        setSize(400, 300);
        getContentPane().setLayout(new FlowLayout());
        final JLabel b1;
        final JRadioButton jrb = new JRadioButton();
        b1 = new JLabel("Simple tooltip 1");

        ActionListener timerTask = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                elapsedTimeMillis = System.currentTimeMillis();
                b1.setText("Timer : " + (elapsedTimeMillis-start)/1000+" ::::: " +sec);
                System.out.println("Timer working: " + sec);
                if(--sec == 0){
                    timer.stop();
                    System.out.println("Timer Stopped");
                }
            }
        };
        timer = new Timer(1000, timerTask);
        System.out.println("Timer Started");
        timer.start();

        getContentPane().add(b1);

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);          
        setVisible(true);
    }

    public static void main(String args[]){
        new TimerOnJLabel();
    }
}

I hope this help.

Smit
  • 4,685
  • 1
  • 24
  • 28
  • Information provided in the answer is good, +1 for that. No need to add one `WindowListener` to close the `JFrame`, when something as simple as writing `frameObject.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)` can do that for you. – nIcE cOw Jan 19 '13 at 09:54
  • @GagandeepBali You are right. But everything happening is inside constructor and in that code I don't have `frameObject`. Moreover I just wanted to show how to start and stop the timer. – Smit Jan 19 '13 at 10:49
  • 1
    Then simply write `setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);/setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);`, that will do, what you did by adding a `WindowListener` :-) – nIcE cOw Jan 19 '13 at 10:50
  • 1
    @GagandeepBali Answer updated. Thanks for information. I dont much play with GUI, thats why. – Smit Jan 19 '13 at 10:54