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 6 of 6

Thread: Timer digit

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

    Default Timer digit

    Hi, I have a problem where I want to get rid of the last digit a timer displays, which I'm not sure why it's displaying. As you can see from the runnable code below, it's adding on another random digit at the end of the time and I'm not sure why. How could I get rid of this last digit?

    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.text.SimpleDateFormat;
    import java.util.Date;
     
    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.NameOfClass;
     
    public class NameOfClass 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("00:00:000");
    	    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_S);
            try {
    			b1.addActionListener(new NameOfClass());
    		} 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{
    			final NameOfClass s = new NameOfClass();
    			final SimpleDateFormat TIME = new SimpleDateFormat("mm:ss:SS");
    			javax.swing.Timer t = new javax.swing.Timer(10, new ActionListener() {
    		        public void actionPerformed(ActionEvent e) {
    				    textField2.setText(TIME.format(new Date(s.getElapsedTime())));
    		        }
    		     });
    			if(e.getSource()==b1)
    			{
    			    s.start();
    			    t.start();
    			}
    		}catch(Exception e1){}
    	}
     
    }


  2. #2
    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: Timer digit

    How do you expect milliseconds to be represented in just two spaces? How would you expect 1.987 seconds to look? Are you simply trying to drop the last digit, or do you expect something else to happen?

    With SimpleDateFormat, you can specify the minimum number of spaces to, not the maximum. So if your format was "mm:s", and you were at 0 minutes and 12 seconds, it's not going to drop the 2. Try it out.

    What the formatter is for, mostly, is padding and arranging of digits- so you can decide to put the seconds first, or the hours last, or whatever. Or you can choose to pad them all out to 5 digits- something like "mmmmm:sssss:SSSSS: would pad smaller numbers with zeroes, so 1 minute, 45 seconds, 523 ms would look like 00001:00045:00523.

    But, I don't think there's a way to specify a "maximum" number of digits, which I think is what you're trying to do, because there's no standard way to drop the digits- do you drop the first digit, the last digit, do you abbreviate somehow? So Java leaves that up to you.

    Actually, upon re-reading your post, are you simply not aware that you're displaying the milliseconds at all?
    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!

  3. #3
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Post Re: Timer digit

    Also, were you aware that there was a Timer class for Swing in java already?

    Timer (Java Platform SE 6)

  4. #4
    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: Timer digit

    Quote Originally Posted by javapenguin View Post
    Also, were you aware that there was a Timer class for Swing in java already?
    Did you not even read his post? He uses a Swing Timer in his code.
    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!

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

    Default Re: Timer digit

    Quote Originally Posted by KevinWorkman View Post
    How do you expect milliseconds to be represented in just two spaces? How would you expect 1.987 seconds to look? Are you simply trying to drop the last digit, or do you expect something else to happen?

    With SimpleDateFormat, you can specify the minimum number of spaces to, not the maximum. So if your format was "mm:s", and you were at 0 minutes and 12 seconds, it's not going to drop the 2. Try it out.

    What the formatter is for, mostly, is padding and arranging of digits- so you can decide to put the seconds first, or the hours last, or whatever. Or you can choose to pad them all out to 5 digits- something like "mmmmm:sssss:SSSSS: would pad smaller numbers with zeroes, so 1 minute, 45 seconds, 523 ms would look like 00001:00045:00523.

    But, I don't think there's a way to specify a "maximum" number of digits, which I think is what you're trying to do, because there's no standard way to drop the digits- do you drop the first digit, the last digit, do you abbreviate somehow? So Java leaves that up to you.

    Actually, upon re-reading your post, are you simply not aware that you're displaying the milliseconds at all?
    Yes, I am aware I'm displaying the milliseconds and yes what I'm trying to do is "set the maximum" number of digits shown. Okay, so you told me why SimpleDateFormat isn't going to work for this. But what I want to know is what should I do so that it "drops the last digit" (or maybe round up, wouldn't that solve it?), if that's at all possible.

  6. #6
    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: Timer digit

    Quote Originally Posted by The_Mexican View Post
    Yes, I am aware I'm displaying the milliseconds and yes what I'm trying to do is "set the maximum" number of digits shown. Okay, so you told me why SimpleDateFormat isn't going to work for this. But what I want to know is what should I do so that it "drops the last digit" (or maybe round up, wouldn't that solve it?), if that's at all possible.
    Like I said, Java leaves it up to you. There are pretty much an infinite number of way to do it- check out the APIs for the String and Math classes for useful functions.
    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. How to Use Timer in Java
    By neo_2010 in forum Java SE API Tutorials
    Replies: 2
    Last Post: August 6th, 2013, 09:49 AM
  2. Ticked Off Timer
    By JavaCow in forum Loops & Control Statements
    Replies: 8
    Last Post: October 30th, 2010, 09:18 AM
  3. Trying to crunch a date to a single digit
    By twitch09 in forum Java Theory & Questions
    Replies: 7
    Last Post: October 15th, 2010, 12:14 AM
  4. need help with Timer and sound
    By amahara in forum AWT / Java Swing
    Replies: 4
    Last Post: February 18th, 2010, 12:22 PM
  5. Timer?
    By TimW in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: October 27th, 2009, 07:43 AM