Timer doesn't work right, never stops

Posted on 2011-10-09
Last Modified: 2012-05-12
I am trying to make a simple timer scheme that I want to use in a larger program.
It is a simple JFrame here, that I created with Oracle JDeveloper that contains a menu
item to bring up a dialog box to change the default timing period of 1 second.

The JButton is supposed to start and stop the counting and reset the timer.

It starts normally, but I cannot stop it. When re-starting the numbers on the JLabel also
jumps around up instead of changing with the chosen time period..

What am I doing wrong here?

package LoopTest;

import java.awt.Font;

import java.awt.Rectangle;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Timer;

import java.util.TimerTask;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JOptionPane;

import javax.swing.SwingConstants;

public class LoopTestFrame extends JFrame {

    JMenuBar menuBar = new JMenuBar();

    JMenu menuFile = new JMenu();

    JMenuItem menuFileExit = new JMenuItem();

    JMenuItem menuSetTimerPeriod = new JMenuItem();

    private JButton jButton1 = new JButton();

    private JLabel jLabel1 = new JLabel();


    Timer timer;  


    private int timerCount;  

    private int timerPeriod = 1;  // Default 1 second period

    private boolean timerRunning = false;

    public LoopTestFrame() {

        try {


        } catch (Exception e) {





    public static void main(String[] args) {

        LoopTestFrame loopTestFrame = new LoopTestFrame();

        loopTestFrame.setLocation(100 , 100);

        loopTestFrame.setSize(250, 230);




    private void jbInit() throws Exception {

        this.setJMenuBar( menuBar );

        this.getContentPane().setLayout( null );

        this.setTitle( "Timer Loop Test" );


        menuFile.setText( "File" );

        menuFileExit.setText( "Exit" );

        menuFileExit.addActionListener( new ActionListener() 

                { public void actionPerformed( ActionEvent ae ) 

                  { fileExit_ActionPerformed( ae ); } } );




        menuSetTimerPeriod.setText( "Set Timer Period" );

        menuSetTimerPeriod.addActionListener( new ActionListener() 

                { public void actionPerformed( ActionEvent ae ) 

                  { setTimerPeriod_ActionPerformed( ae ); } } );



        jButton1.setText("Start Timer");

        jButton1.setBounds(new Rectangle(60, 20, 125, 40));

        jButton1.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {





        jLabel1.setBounds(new Rectangle(15, 90, 215, 25));



        jLabel1.setFont(new Font("Tahoma", 1, 14));

        menuFile.add( menuSetTimerPeriod );

        menuFile.add( menuFileExit );


        menuBar.add( menuFile );

        this.getContentPane().add(jLabel1, null);

        this.getContentPane().add(jButton1, null);


    public void fileExit_ActionPerformed(ActionEvent e) {





    public void setTimerPeriod_ActionPerformed(ActionEvent e){


        String dialog = JOptionPane.showInputDialog(null, "Please enter looping interval in seconds", "Looping Interval", JOptionPane.CANCEL_OPTION);

        timerPeriod = Integer.valueOf(dialog);




    private void jButton1_actionPerformed(ActionEvent e) {


        timer = new Timer();

        timerCount = 0;


        if (timerRunning == false){

            timerRunning = true;    // change it to opposite

            jButton1.setText("Stop Timer");


         /*   timer.scheduleAtFixedRate(new LoopTask(),      // Use scheduleAtFixedRate method when time synchronization is more important                         

                          0,        //initial delay

                         timerPeriod * 1000);  //subsequent rate (milliseconds)  */



              timer.schedule(new LoopTask(),      // Use scheduleAtFixedRate method when time synchronization is more important                         

                                       0,        //initial delay

                                      timerPeriod * 1000);  //subsequent rate (milliseconds)




            timerRunning = false;  // change it to opposite

            jButton1.setText("Start Timer");

            timer.cancel(); // Stop timer

            System.out.println("Timer Stopped.");

            timerCount = 0;




    // LoopTask is an inner class, implementing TimerTask class run() method:

        class LoopTask extends TimerTask {

            public void run() {

                    System.out.println("Run timed method");






Open in new window

Question by:AttilaB
    LVL 86

    Accepted Solution

    You're confusing the app by creating the Timer irrespective of whether it's already running. Try
    if (timerRunning == false) {
    	    timer = new Timer();
    	    timerRunning = true; // change it to opposite

    Open in new window


    Author Closing Comment

    Thank you. This fixes it.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Live - One-on-One Java Help from Top Experts

    Solve your toughest problems, fast.
    Java experts are online now and ready to help you.

    For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
    An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
    Video by: Michael
    Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
    Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

    794 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now