Results 1 to 16 of 16
  1. #1
    Chris Rice is offline Member
    Join Date
    Mar 2010
    Posts
    10
    Rep Power
    0

    Angry I need help with timers

    I'm making a program that needs to update data in an array every second, I have been playing around with the timer class for about an hour now and gotten nowhere.

    Java Code:
           int interval = 1000;
           class MyListener implements ActionListener{
               public void actionPerformed(ActionEvent event){
                    Traffic2 [10] [0] += 1;     
               }
           }
           MyListener listener = new MyListener();
           Timer t = new Timer(interval, listener);
           t.start();
    I've already set up and declared the array Traffic2 but when I try to run this it does not update it at all and just crashes. Is there another timing method I should be using and/or what am I doing wrong. I am so confused. :confused:

  2. #2
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    What you mean by crash? Did you comes with an error, if so please send it here. It's not possible to comment on this without more information.

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Swing timer,

    Java Code:
            Timer timer = new Timer(1, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    // process
                }
            });
            timer.start();
    check the parameter list.

  4. #4
    Chris Rice is offline Member
    Join Date
    Mar 2010
    Posts
    10
    Rep Power
    0

    Default

    Java Code:
    public class Main {
         public static void main(String[] args) {
              //A bunch of declaring arrays and variables such as:
             int [][] Traffic2 = new int [100][2];
             //Then after declaring and setting up all of those, I want data to update within them every second. 
             //I've tried using this code that I found in my java book:
             int interval = 1000;
             int updater;
             class MyListener implements ActionListener{
                  public void actionPerformed(ActionEvent event){
                       //So this is where it says to do the actions so I put
                       updater = randomGenerator.nextInt(100)+5;
                       Traffic2 [1] [0] = updater;
                       //The error this comes up with is:
                       //"Local variable updater is accessed from within inner class; needs to be declared final."
                       //It also comes up with these errors for the other stuff I used in here
                  }
              }
              MyListener listener = new MyListener();
              Timer t = new Timer(interval, listener);
              t.start();
        }
    }
    Hope this helps get to the root of the problem, this is my first experience with timers in java, is there another way to do this or am I just missing something from this method. Thanks to anyone who replies. :)

  5. #5
    Chris Rice is offline Member
    Join Date
    Mar 2010
    Posts
    10
    Rep Power
    0

    Default Ok I got something to work right

    I found out how to access the variable from outside in my timer but it still doesn't do exactly what I want, the output for this code is that it just displays the CarsTunnel as it was before, I want it to add one to the variable every second and then display it every second. It seems to me like this just stops the program without even activating the timer. So how do I get the timer to start and keep going?
    Java Code:
    int interval = 1000;
    class MyListener implements ActionListener{
         public void actionPerformed(ActionEvent event){
              Main Variable = new Main();
                   Variable.CarsTunnel += 1;
              }
         }
         MyListener listener = new MyListener();
         Timer t = new Timer(interval, listener);
         t.start();
         System.out.println(CarsTunnel);

  6. #6
    Chris Rice is offline Member
    Join Date
    Mar 2010
    Posts
    10
    Rep Power
    0

    Default

    please anyone?

  7. #7
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Chris Rice View Post
    I found out how to access the variable from outside in my timer but it still doesn't do exactly what I want, the output for this code is that it just displays the CarsTunnel as it was before, I want it to add one to the variable every second and then display it every second. It seems to me like this just stops the program without even activating the timer. So how do I get the timer to start and keep going?
    Java Code:
    int interval = 1000;
    class MyListener implements ActionListener{
         public void actionPerformed(ActionEvent event){
              Main Variable = new Main();
                   Variable.CarsTunnel += 1;
              }
         }
         MyListener listener = new MyListener();
         Timer t = new Timer(interval, listener);
         t.start();
         System.out.println(CarsTunnel);
    In your actionPerformed( ... ) method you create a new Main Variable object every time the method is excecuted so any previously created Main object is lost for the posterity (the new object is freshly initialized over and over again). Make your Main Variable object a member of your enclosing class and make your actionPerformed method use that same object over and over again.

    kind regards,

    Jos

  8. #8
    Chris Rice is offline Member
    Join Date
    Mar 2010
    Posts
    10
    Rep Power
    0

    Default

    Thanks for the help :) I understand what you're saying here however it still does not solve my problem. It does not ever start the timer it just outputs all of my other stuff then seems like it totally skips over this timer. It says build successful but still no reference to the timer :confused: So how do I get this timer to work?
    Last edited by Chris Rice; 03-07-2010 at 06:46 PM.

  9. #9
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Chris Rice View Post
    Thanks for the help :) I understand what you're saying here however it still does not solve my problem. It does not ever start the timer it just outputs all of my other stuff then seems like it totally skips over this timer. It says build successful but still no reference to the timer :confused: So how do I get this timer to work?
    Can you show us (the relevant parts of) your latest code? I don't understand your remark "still no reference to the timer". A timer is a simple thing: when the alarm clock rings its ActionListener is called and the alarm clock is set again. This simple process repeats itself over and over again.

    kind regards,

    Jos

  10. #10
    Chris Rice is offline Member
    Join Date
    Mar 2010
    Posts
    10
    Rep Power
    0

    Default

    Java Code:
    public class Main {
    
        public double TotalLength;
        public double TunnelExitToMerge;
        public double BackupLimit;
        public int CarsLovePass;
        public int [][] Traffic1;
        public int CarsEisTunnel;
        public int [][] Traffic2;
        public int CarSpeed1;
    
        public static void main(String[] args) {
    
           Random randomGenerator = new Random();
           // Figures out length in inches for the required variables
           Main Variables = new Main();
           double TotalLength = 12.04;
           double TunnelExitToMerge = .78;
           double BackupLimit = 11.04;
           int loop = 0;
    
           TotalLength *= 63360;
           TunnelExitToMerge *= 63360;
           BackupLimit *= 63360;
    
           /*Makes the larger numbers easier to read by adding commas where
                necessary*/
           DecimalFormat df = new DecimalFormat("#,##0");
           /*Declares the array for cars coming out of Loveland Pass
                1st column is for speed, 2nd for car length(declared later)*/
           int CarsLovePass = randomGenerator.nextInt(5)+5;
           int [][] Traffic1 = new int [CarsLovePass][2];
           /*Declares the array for cars coming out of Eisenhower Tunnel
                1st column is for speed, 2nd for car length(declared later)*/
           int CarsEisTunnel = randomGenerator.nextInt(5)+5;
           int [][] Traffic2 = new int [CarsEisTunnel][2];
           
           //Declares speed for all cars coming out of the pass(in/s)
           int CarSpeed1;
           int i;
           int j;
           for (loop = 0; loop<Traffic1.length; loop++){
               CarSpeed1 = randomGenerator.nextInt(25)+ 40;
               CarSpeed1 *= 176;
               Traffic1 [loop] [0] = CarSpeed1;
           }
           
           //Declares speed for all cars coming out of the tunnel(in/s)
           int CarSpeed2;
           int Randomizer;
           for (loop = 0; loop<Traffic2.length; loop++){
               Randomizer = randomGenerator.nextInt(10) + 1;
               if (Randomizer == 1){
                   i = 10;
                   j = 30;
               }
               else{
                   i = 20;
                   j = 35;
               }
               CarSpeed2 = randomGenerator.nextInt(i)+ j;
               CarSpeed2 *= 176;
               Traffic2 [loop] [0] = CarSpeed2;
           }
    
           //Declares length of all cars coming out of the Pass (in)
           int CarLength1;
           for (loop = 0; loop<Traffic1.length; loop++){
               CarLength1 = randomGenerator.nextInt(65) + 170;
               Traffic1 [loop] [1] = CarLength1;
           }
    
           //Declares length of all cars coming out of the tunnel (in)
           int CarLength2;
           for (loop = 0; loop<Traffic2.length; loop++){
               CarLength2 = randomGenerator.nextInt(30)+180;
               Traffic2 [loop] [1] = CarLength2;
           }
           System.out.println("There are a total of "
                   + df.format((CarsEisTunnel + CarsLovePass)) + " Cars. ");
    
           System.out.println(df.format(CarsEisTunnel) +
                   " are traveling in Eisenhower Tunnel and " +
                   df.format(CarsLovePass) + " that are traveling"
                   + " on Loveland Pass");
           int WhichCar;
           int loop2 = 1;
           int [][] AllCars = new int [Traffic1.length + Traffic2.length] [2];
           if (Traffic1.length < Traffic2.length){
                for (loop = 0; loop < CarsEisTunnel; loop++){
                    WhichCar = Traffic2 [loop][0];
                    AllCars [loop2][0] = WhichCar;
                    if (loop2 < (AllCars.length - 2)){
                        loop2 +=2;
                    }
                }
                loop2 = 0;
                for (loop = 0; loop < CarsLovePass; loop++){
                    WhichCar = Traffic1 [loop][0];
                    AllCars[loop2][0] = WhichCar;
                    if (loop2 < (AllCars.length - 2) && loop < Traffic2.length - 2){
                       loop2 +=2;
                    }
                    if (loop2 < (AllCars.length - 2) && loop >= Traffic2.length -2){
                        loop2 += 1;
                    }
    
                }
                loop2 = 0;
           }
           else {
                for (loop = 0; loop < CarsLovePass; loop++){
                    WhichCar = Traffic1 [loop][0];
                    AllCars [loop2][0] = WhichCar;
                    if (loop2 < (AllCars.length - 2)){
                        loop2 +=2;
                    }
                }
                loop2 = 0;
                for (loop = 0; loop < CarsEisTunnel; loop++){
                    WhichCar = Traffic2 [loop][0];
                    AllCars[loop2][0] = WhichCar;
                    if (loop2 < (AllCars.length - 2) && loop < Traffic1.length){
                       loop2 += 2;
                    }
                    if (loop2 < (AllCars.length - 2) && loop >= Traffic1.length -2){
                        loop2 += 1;
                    }
    
                }
                loop2 = 0;
           }
    
    
           //WhichCar = randomGenerator.nextInt()
    
          
            Variables.TotalLength = TotalLength;
            Variables.TunnelExitToMerge = TunnelExitToMerge;
            Variables.BackupLimit = BackupLimit;
            Variables.CarsLovePass = CarsLovePass;
            Variables.Traffic1 = Traffic1;
            Variables.CarsEisTunnel = CarsEisTunnel;
            Variables.Traffic2 = Traffic2;
    
           int interval = 1000;
           class MyListener implements ActionListener{
               Main Variable = new Main();
               public void actionPerformed(ActionEvent event){
                   Variable.CarsEisTunnel += 1;
               }
           }
           MyListener listener = new MyListener();
           Timer t = new Timer(interval, listener);
           t.start();
         
        }
    
    
    }
    There it is :eek:

  11. #11
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Remove that Main Variable from your ActionListener, your actionPerformed( ... ) method is manipulating the wrong variable: simply make the body of that method:

    Java Code:
    Main.this.CarsEisTunnel += 1;
    kind regards,

    Jos

  12. #12
    Chris Rice is offline Member
    Join Date
    Mar 2010
    Posts
    10
    Rep Power
    0

    Default

    Ok.... I did that but the timer still doesn't go. No errors or anything of the sort it just displays the other things and says build successful. Is there something I have to do to keep the timer running?

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Chris Rice View Post
    Ok.... I did that but the timer still doesn't go. No errors or anything of the sort it just displays the other things and says build successful. Is there something I have to do to keep the timer running?
    That timer works; Sun wouldn't release code that doesn't work so bluntly; study this snippet of code: it uses a timer and a counter is incremented, just like in your code:

    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.Timer;
    
    public class TimerTest {
    
    	int counter;
    
    	ActionListener listener= new ActionListener() {
    		public void actionPerformed(ActionEvent ae) {
    			counter++;
    		}
    	};
    	
    	Timer t= new Timer(1000, listener);
    	
    	public TimerTest() {
    		t.start();
    		while (true) {
    			try {
    				Thread.sleep(900);
    				System.out.println(counter);
    			}
    			catch (InterruptedException ie) {
    				ie.printStackTrace();
    			}
    		}
    	}
    	
    	public static void main(String args[]) {
    		new TimerTest();
    	}
    
    }
    kind regards,

    Jos

  14. #14
    Chris Rice is offline Member
    Join Date
    Mar 2010
    Posts
    10
    Rep Power
    0

    Default Thank you so much!!!

    It finally works :) thanks for all the help you've given me :)

  15. #15
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Chris Rice View Post
    It finally works :) thanks for all the help you've given me :)
    Good; congrats. What was your mistake and how did you correct it?

    kind regards,

    Jos

  16. #16
    salt is offline Member
    Join Date
    Sep 2013
    Posts
    1
    Rep Power
    0

    Default Re: I need help with timers

    Hi All, Need help in Timers purge in java.

    Whenever i call purge i am getting zero even after cancelling the task. The task is gettting cancelled. Could anyone please help on this.

    Sample program :

    import java.util.*;
    class root

    {

    public static void main(String[]args)

    {
    Timer timer = new Timer();
    TimerTask timertask = new timerTaskclass();
    timer.schedule(timertask,5000);
    timertask.cancel();
    System.out.println("The no of jobs removed is::"+timer.purge());
    }
    }

    class timerTaskclass extends TimerTask
    {

    public void run()

    {

    System.out.println("XXXXXXXXX");

    }

    }

    Thanks
    Salt

Similar Threads

  1. Help - Swing Timers, Two Keypresses
    By Gheta in forum AWT / Swing
    Replies: 2
    Last Post: 07-29-2009, 09:23 PM
  2. Swing Timers Issue.
    By killpoppop in forum AWT / Swing
    Replies: 4
    Last Post: 03-09-2009, 11:17 PM
  3. Question on swing timers
    By Samgetsmoney in forum New To Java
    Replies: 5
    Last Post: 02-20-2009, 07:34 AM
  4. Replies: 0
    Last Post: 12-31-2008, 02:20 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •