Timer start/stop parameters

12,628

Solution 1

As you want to start and stop the timer at different places in the code you should make it member variable. This will fix the problem where you are trying to stop the timer inside the action listener.

The variable p1Laps will not change in the constructor (after you have initialized it to 0) so you need to start the timer where you change the value of plLaps. I am not sure if it is safe to call timer.start() from another thread (Move1). So it may be safer to start timer with SwingUtilities.invokeLater().

Solution 2

Quick fix:

Rather than

timer.stop();

Do

((Timer)e.getSource()).stop();

The ActionEvent's getSource method will return a reference to the object that calls the actioPerformed method (the Timer), so this should work.

There may be other issues with your code including your background thread without a Thread.sleep(...), your use of KeyListeners rather than Key Binding, your adding a KeyListener in a background thread,...

Share:
12,628
Speakr
Author by

Speakr

Learning Java as a data analysis tool and a game development tool.

Updated on June 04, 2022

Comments

  • Speakr
    Speakr almost 2 years

    I've made leaps and bounds in skill and progress since joining this community. You all are a huge help. I'm having trouble with giving a timer that I've implemented certain parameters for when it starts and stops.

    I either get errors saying "the local variable timer may not have been initialized" or I get no errors, but nothing happens. Maybe I have the timer in the wrong place?

    If I put timer.start(); in the constructor too everything works fine, but then the timer has to start when the program is initialized. I would really like to have the timer not start until a certain parameter is met. Say, for instance, until the int p1Laps=1; but if I place timer.start(); into an if-statement in the constructor (i.e. if(p1Laps>=1) { timer.start(); } the timer doesn't ever start.

    I've tried placing timer.start(); in various places and have either gotten no response or generated an error about the lack of local variable timer.

    A second, somewhat related problem I have is the inability to put any parameters in place to call on timer.stop(); without getting the aforementioned "local variable timer may not have been initialized" error. I've left timer.stop(); where I think it needs to be in the code, but it receives that error.

    So in short, I want to be able to tell the timer to start when a parameter is met, namely when a player has completed a lap. And I want to be able to tell the timer to stop when it reaches a value.

    Thanks in advance for the great advice I'm sure I'll receive. Note: this is not the whole code, just relevant information.

    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    
    public class RacerDoom extends JFrame {
        int counter = 0;
        int p1Laps = 0;
    public RacerDoom() {
            //create JFrame
            super("Racer Doom Squared");
            setSize(WIDTH,HEIGHT);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            //set up Timer
            final Timer timer=new Timer(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if(counter>=10) {
                        timer.stop(); //error here reads "local variable timer may
                                        //not have been initialized"
                    }
                    else{
                       counter++;
                       }
                    System.out.println(counter);
                }
            });
            //inner class threads
            Move1 m1 = new Move1();
            m1.start();
            //start timer
            if(p1Laps>=1) {
                timer.start(); //error here is that timer will not start when
                                //p1Laps>=1
            }
        }
        private class Move1 extends Thread implements KeyListener {
            public void run() {
                addKeyListener(this);
                while(true) {
                    try {
                        repaint();
                        //collisions
                        if(p1.intersects(finishtop)&&p1Direction==UP&&p1cross!=true){
                            p1cross=true;
                            p1Laps++;
                            p1Boost++;
                            counter=0;
                            System.out.println(p1Laps);
                        }
                        if(p1.intersects(finishtop)==false) {
                            p1cross=false;
                        }
        public static void main (String [] args) {
    
            new RacerDoom();
        }
    }
    
  • Speakr
    Speakr over 12 years
    Sorry, my background thread does have a Thread.sleep(...); I just forgot to include it.
  • Speakr
    Speakr over 12 years
    I need to look into SwingUtilities.invokeLater() as I've seen it mentioned several times on this site but am completely unfamiliar with it.
  • Sam YC
    Sam YC over 11 years
    Hi, can I ask some questions? In java, if we assign a timer object to null value (timer = null;) without calling timer.stop() prior it, will the timer stop firing to the listener?
  • Ashwinee K Jha
    Ashwinee K Jha over 11 years
    No it will not stop the timer as the timer reference will still be present in the internal queue or timers to be triggered (maintained by internal thread).