Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Updating timer

  1. #1
    Member
    Join Date
    Feb 2010
    Posts
    81
    Thanks
    18
    Thanked 1 Time in 1 Post

    Default Updating timer

    Hi, I'm having trouble getting my timer to be continuously updating. Once I click the button to start the timer it just shows 0. However, it shows the correct time after you finish.

    public long getElapsedTime() {
            long elapsed;
            if (running) {
                 elapsed = (System.currentTimeMillis() - startTime);
            }
            else {
                elapsed = (stopTime - startTime);
            }
            return elapsed;
        }
    GameClient2 s = new GameClient2();
    if(e.getSource()==b4)
    {
    s.start();
    String get = Long.toString(s.getElapsedTime());
    		    textField2.setText(get);                 //this just updates it once...
    }
    if(e.getSource()==b1)
    {
    s.stop();
    					double et = s.getElapsedTime();
    					double sec = et/1000;
    					JOptionPane.showMessageDialog(null, "You got it! Your elapsed time in seconds was: "+sec,"Correct!",JOptionPane.INFORMATION_MESSAGE);
    					System.exit(0);
    }

    So I know that I'm only updating it once, but I can think of no other way to do this.


  2. #2
    Member DanBrown's Avatar
    Join Date
    Jan 2011
    Posts
    134
    My Mood
    Confused
    Thanks
    1
    Thanked 12 Times in 12 Posts

    Default Re: Updating timer

    if(e.getSource()==b4)
    {
    s.start();
    String get = Long.toString(s.getElapsedTime());
    textField2.setText(get); //this just updates it once...
    }

    the code written above says that change the time elapsed only when someone click on the button.

    the above line will be execute only once after clicking on the button b4.

    Your thread is not calling the Text box update function regularly then how can you expect that time will be updated.
    Thanks and Regards
    Dan Brown

    Common Java Mistakes

  3. #3
    Member
    Join Date
    Feb 2010
    Posts
    81
    Thanks
    18
    Thanked 1 Time in 1 Post

    Default Re: Updating timer

    Quote Originally Posted by DanBrown View Post
    the code written above says that change the time elapsed only when someone click on the button.

    the above line will be execute only once after clicking on the button b4.

    Your thread is not calling the Text box update function regularly then how can you expect that time will be updated.
    Ya, I realize that I am doing this, but my question is how do it get so that when you click the button the time in the text box updates consistently as the timer continues.

  4. #4
    Member DanBrown's Avatar
    Join Date
    Jan 2011
    Posts
    134
    My Mood
    Confused
    Thanks
    1
    Thanked 12 Times in 12 Posts

    Default Re: Updating timer

    s.start();
    this is calling run method of thread.

    What you can do is make a global flag which will be true when you click on start button and will be false when you click on stop button.

    and in run

    put a loop which will continuously update the time till the flag is true

    i.e

     
              boolean isStarted;
     
              void run(){
     
                        while(isStarted){
     
     
                               //put your time update code here
     
     
                        }
     
              }
    Thanks and Regards
    Dan Brown

    Common Java Mistakes

  5. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Updating timer

    You could also simply use an actual Timer, calling its start and stop functions when appropriate. Which approach is best is up to you. Google is your friend.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. #6
    Member
    Join Date
    Feb 2010
    Posts
    81
    Thanks
    18
    Thanked 1 Time in 1 Post

    Default Re: Updating timer

    Quote Originally Posted by DanBrown View Post
    this is calling run method of thread.

    What you can do is make a global flag which will be true when you click on start button and will be false when you click on stop button.

    and in run

    put a loop which will continuously update the time till the flag is true

    i.e

     
              boolean isStarted;
     
              void run(){
     
                        while(isStarted){
     
     
                               //put your time update code here
     
     
                        }
     
              }
    I did this and now it just goes into the while loop once the timer is started and is stuck there forever, you can't click any buttons and the timer isn't even updating anyway.

  7. #7
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Updating timer

    Did you put that in another Thread, or are you running that on the EDT? We can't really comment on your code unless you post it as an SSCCE (that's a link).
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  8. #8
    Member
    Join Date
    Feb 2010
    Posts
    81
    Thanks
    18
    Thanked 1 Time in 1 Post

    Default Re: Updating timer

    Quote Originally Posted by KevinWorkman View Post
    Did you put that in another Thread, or are you running that on the EDT? We can't really comment on your code unless you post it as an SSCCE (that's a link).
    Okay, here is the shortest possible program that I could make that still demonstrates my problem while being runnable:

    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
     
    import javax.swing.AbstractButton;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SpringLayout;
     
    import layout.GameClient2;
     
    public class testing extends JPanel implements ActionListener{
    	protected static JButton b1;
    	static JTextField textField2;
        static JFrame frame = new JFrame("Frame");
    	//Start timer setup:
    	public static long startTime = 0;
        public static long stopTime = 0;
        public static boolean running = false;
        public void start() {
            this.startTime = System.currentTimeMillis();
            this.running = true;
        }
        public void stop() {
            this.stopTime = System.currentTimeMillis();
            this.running = false;
        }
        public long getElapsedTime() {
            long elapsed;
            if (running) {
                 elapsed = (System.currentTimeMillis() - startTime);
            }
            else {
                elapsed = (stopTime - startTime);
            }
            return elapsed;
        }
     
        public long getElapsedTimeSecs() {
            long elapsed;
            if (running) {
                elapsed = ((System.currentTimeMillis() - startTime) / 1000);
            }
            else {
                elapsed = ((stopTime - startTime) / 1000);
            }
            return elapsed;
        }
        //End timer setup
    	public static void main (String args[])
    	{
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGame();
                }
            });
    	}
    	public static void createAndShowGame() {
    		textField2 = new JTextField("0:00:00");
    	    textField2.setEditable(false);
    	    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	    Container contentPane = frame.getContentPane();
    	    SpringLayout layout = new SpringLayout();
    	    contentPane.setLayout(layout);
    	    b1 = new JButton("Start");
    	    b1.setVerticalTextPosition(AbstractButton.CENTER);
    	    b1.setHorizontalTextPosition(AbstractButton.LEADING);
    	    b1.setMnemonic(KeyEvent.VK_D);
            try {
    			b1.addActionListener(new GameClient2());
    		} catch (Exception e) {}
    		contentPane.add(textField2);
    		contentPane.add(b1);
    	    //SET HEIGHT/WIDTH
    	       layout.putConstraint(SpringLayout.WEST, textField2,
    	                            10,
    	                            SpringLayout.WEST, contentPane);
    	       layout.putConstraint(SpringLayout.NORTH, textField2,
    	                            242,
    	                            SpringLayout.NORTH, contentPane);
    	    //END SET HEIGHT/WIDTH
    	    //SET HEIGHT/WIDTH
    	       layout.putConstraint(SpringLayout.WEST, b1,
    	                            197,
    	                            SpringLayout.WEST, contentPane);
    	       layout.putConstraint(SpringLayout.NORTH, b1,
    	                            262,
    	                            SpringLayout.NORTH, contentPane);
    	    //END SET HEIGHT/WIDTH
    	    frame.pack();
    	    frame.setSize(458, 325);
    	    frame.setVisible(true);
    	}
    	public void actionPerformed(ActionEvent e) {
    		try{
    			GameClient2 s = new GameClient2();
    			if(e.getSource()==b1)
    			{
    			    s.start();
    			    //Here, these two lines of code seem to be the problem, how do I fix this so that the time in the textField2 is continuously updating?:
    			    String get = Long.toString(s.getElapsedTime());
    			    textField2.setText(get);
    			    //
    			}
    		}catch(Exception e1){}
    	}
     
    }

  9. #9
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Updating timer

    I appreciate the effort, but that's still not an SSCCE. For example, what is GameClient2 doing? And where is your Timer code?

    I predict that you want to put the textField2.setText() line inside a Swing Timer. But that's just guessing.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  10. #10
    Member
    Join Date
    Feb 2010
    Posts
    81
    Thanks
    18
    Thanked 1 Time in 1 Post

    Default Re: Updating timer

    I wasn't sure how to use a swing timer so, as you can see, I set it up so that I can call .getElapsedTime on anything that is able to 'start' such as the variable s in the program. It should work fine, and it does, for example, if you were to add a button that stops the 'timer' in this code and have it print out what the elapsed time is (s.getElapsedTime()) it works fine. However, my problem is I can't get a textField2 to continuously show the timer running, and I don't think it would be any different with a swing timer anyway.

  11. #11
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Updating timer

    If you want something to continuously happen, then that's what a Swing Timer is for. How would it not be any different? You don't have any code here that would happen continuously, so what do you expect to happen? Googling "java Swing Timer" would have been a good start, as it led to this tutorial: How to Use Swing Timers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. Updating GUI dynamically
    By KrisTheSavage in forum AWT / Java Swing
    Replies: 2
    Last Post: August 29th, 2010, 08:23 AM
  2. Problem with updating empty JTable
    By byubi in forum AWT / Java Swing
    Replies: 1
    Last Post: May 15th, 2010, 02:06 AM
  3. MouseMotionListener is not updating my variable
    By olemagro in forum AWT / Java Swing
    Replies: 1
    Last Post: February 8th, 2010, 03:44 PM
  4. updating EDT with thread swingworker/invokeLater ?
    By mdstrauss in forum AWT / Java Swing
    Replies: 0
    Last Post: October 11th, 2009, 04:52 AM
  5. updating database
    By gurpreetm13 in forum JDBC & Databases
    Replies: 3
    Last Post: October 9th, 2009, 11:43 AM