[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Timer doesn't work right, never stops

Posted on 2011-10-09
2
Medium Priority
?
333 Views
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 {

            jbInit();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    

    public static void main(String[] args) {

        LoopTestFrame loopTestFrame = new LoopTestFrame();

        loopTestFrame.setLocation(100 , 100);

        loopTestFrame.setSize(250, 230);

        loopTestFrame.setResizable(false);

        loopTestFrame.setVisible(true);

    }



    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) {

                    jButton1_actionPerformed(e);

                }

            });

        jLabel1.setText("0");

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

        jLabel1.setHorizontalAlignment(SwingConstants.CENTER);

        jLabel1.setHorizontalTextPosition(SwingConstants.CENTER);

        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) {

        System.exit(0);

    }

    

  

    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)

        }

        else

        {

            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");

                    timerCount++;

                    jLabel1.setText(Integer.toString(timerCount));

                }

            }   

}

Open in new window

0
Comment
Question by:AttilaB
2 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 2000 total points
ID: 36938820
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

0
 

Author Closing Comment

by:AttilaB
ID: 36938887
Thank you. This fixes it.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month18 days, 14 hours left to enroll

834 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