Timer doesn't work right, never stops

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

Who is Participating?
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

AttilaBAuthor Commented:
Thank you. This fixes it.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.