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

    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"

    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

    public void actionPerformed (ActionEvent e){
    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
    Voorschoten, the Netherlands
    Blog Entries
    Rep Power

    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:
    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,

    Build a wall around Donald Trump; I'll pay for it.

Similar Threads

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