Results 1 to 2 of 2
  1. #1
    cheongchye is offline Member
    Join Date
    Oct 2013
    Posts
    1
    Rep Power
    0

    Default Learning about Timer

    I wrote the code below & when i run the program, it just print "Second elapsed : 1 " and terminated. It doesn't keep printing
    "Second elapsed : 2"
    "Second elapsed : 3"
    "Second elapsed : 4"
    ....
    ....
    etc

    However, if i change the timer delay to 500 ms (or anything less than 980 ms) the program works. What is the problem?

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

    public class TestTimer2 extends JFrame implements ActionListener{

    private Timer t;
    public int ticks = 0, sec =0;

    public TestTimer2(){

    t = new Timer(1000, this); //1000 ms does not work but 500 ms works
    t.start();
    }

    public void actionPerformed (ActionEvent e){
    ticks++;
    System.out.println("Second elapsed : " + ticks);
    }


    public static void main(String [] args)
    {
    TestTimer2 tt = new TestTimer2();
    }


    }

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

    Default Re: Learning about Timer

    You are using a Swing timer; those timers use 'daemon threads' (read the API documentation for that Timer class); before it can start, your main( ... ) method has already finished so the daemon threads will be killed as well. For a quick fix add the following line to your main( ... ) method:

    Java Code:
    while(true);
    The main( ... ) will never terminate so your Timer can do what it wants to do. Also have a look at the java.util.Timer class; you probably want that one ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Timer And Timer Task
    By Ashish_jain in forum New To Java
    Replies: 3
    Last Post: 06-22-2011, 10:41 AM
  2. Replies: 12
    Last Post: 06-14-2011, 05:55 PM
  3. Stopping a Timer from Inside the timer
    By krishnan in forum Java Applets
    Replies: 2
    Last Post: 10-05-2010, 12:15 AM
  4. e-learning
    By Vipan Konnect in forum Advanced Java
    Replies: 3
    Last Post: 11-21-2009, 05:29 PM
  5. Replies: 0
    Last Post: 04-04-2008, 03:46 PM

Posting Permissions

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