1

I have the required code for the stopwatch here. All i want is get rid of the Swing part here and display the same output in console. Can anybody help?

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.text.*;

public class ElapsedTime extends JFrame
{
JLabel time;

long startTime = System.currentTimeMillis();

ElapsedTime()
{
setSize(380,200);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridBagLayout());

time = new JLabel("");

time.setFont(new Font("SansSerif",Font.BOLD, 36));

time.setForeground(Color.MAGENTA);

add(time);

//starting new Thread which will update time
new Thread(new Runnable()
{
public void run() 
{ try 
{
updateTime(); 
} 
catch (Exception ie) 
{ }
}
}).start();
}

public void updateTime()
{
try
{
while(true)
{
//geting Time in desire format
time.setText(getTimeElapsed());
//Thread sleeping for 1 sec
Thread.currentThread().sleep(1000);
}
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}
}

public String getTimeElapsed()
{
long elapsedTime = System.currentTimeMillis() - startTime;
elapsedTime = elapsedTime / 1000;

String seconds = Integer.toString((int)(elapsedTime % 60));
String minutes = Integer.toString((int)((elapsedTime % 3600) / 60));
String hours = Integer.toString((int)(elapsedTime / 3600));

if (seconds.length() < 2)
seconds = "0" + seconds;

if (minutes.length() < 2)
minutes = "0" + minutes;

if (hours.length() < 2)
hours = "0" + hours;

return minutes+":"+seconds;
}

public static void main(String[] args) 
{
JFrame obj = new ElapsedTime();
obj.setVisible(true);
}
}
4
  • So you want your program to count time, basically? Must it clear the console when updating the time, or would it be acceptable to print each increment of time on a new line? Commented Aug 16, 2010 at 6:31
  • Java: time elapsed counter using Swing - BTW - is this homework? Commented Aug 16, 2010 at 6:41
  • Yes. I want my program to count time, simply. And it should clear the console when updating time(like 00:01,00:02,00:03...so on).Thanks Commented Aug 16, 2010 at 6:48
  • @ Andreas_D No!This isn't a homework. I'm quite new to Java. I have the required code but i want to get rid of Swing and do the same thing in a console. Commented Aug 16, 2010 at 6:51

4 Answers 4

3

The keys are:

a.) Finding which character to write to the console in order to remove the most recently-written character (\b, or \010 in ASCII)
b.) Realising that you need to remember how many characters you've written to the console the last time you updated it
c.) Remembering to use print instead of println

public class Test {

  public static void main(String[] args) throws InterruptedException {
    int charsWritten = 0;
    long start = System.currentTimeMillis();
    while (1 > 0) {
      Thread.sleep(1000);
      long elapsedTime = System.currentTimeMillis() - start;
      elapsedTime = elapsedTime / 1000;

      String seconds = Integer.toString((int) (elapsedTime % 60));
      String minutes = Integer.toString((int) ((elapsedTime % 3600) / 60));
      String hours = Integer.toString((int) (elapsedTime / 3600));

      if (seconds.length() < 2) {
        seconds = "0" + seconds;
      }

      if (minutes.length() < 2) {
        minutes = "0" + minutes;
      }

      if (hours.length() < 2) {
        hours = "0" + hours;
      }

      String writeThis = hours + ":" + minutes + ":" + seconds;

      for (int i = 0; i < charsWritten; i++) {
        System.out.print("\b");
      }
      System.out.print(writeThis);
      charsWritten = writeThis.length();
    }
  }
}

Note: you could be more efficient by only clearing the console up to only the characters you are changing but I figure you're not going to get that much of a speed improvement.

Sign up to request clarification or add additional context in comments.

5 Comments

I'm getting the following out put exactly: 00:00:0100:00:0200:00:0300:00:0400:00:0500:00:0600:00:0700:00:0800:00:0900:00:1000:00:1100:00:1200:00:1300:00:1400:00:1500:00:1600:00:1700:00:18 ???
@Maxood - It could be because the \010 is the ASCII code for backspace and your console isn't ASCII? Anyway, I've fixed my code to use \b instead. Hopefully that will work for you.
@Catchwa I'm still getting a similar output and not the required one.
@Maxood - What OS? What Java version? Where are you running it (e.g. within an IDE - if so, which one)? What is the native language of your OS?
@Catchwa The OS is android. Java version is 1.6. I'm running my project in Eclipse and the native language of my OS is Java.
2

Have a look at StopWatch from Apache Commons. It should fulfill your needs.

Comments

0

Here's something that i have figured out myself a little while ago:

public class DelayExample{
  static int i,j;
  public static void main(String[] args){

    for (j= 0; j>=0; j++)
    {
    for (i = 0; i < 60; i++)
      {
      System.out.println(j+":" + i);

      try
      {
        Thread.sleep(1000);        

            }catch (InterruptedException ie)
            {
        System.out.println(ie.getMessage());
            }
        }

    }
    }
} 

Now i want the clear screen code in Java now. Also i think i have to use System.out.print() instead.

Comments

0

So there a Swing-free solution:

public class ElapsedTime{

long startTime = System.currentTimeMillis();

public ElapsedTime() {
    try {
        while (true) {
            //Clear Console
            for (int i = 0; i < 25; i++)    
                System.out.println();
            // geting Time in desire format
            System.out.println(getTimeElapsed());
            // Thread sleeping for 1 sec
            Thread.currentThread().sleep(1000);
        }
    } catch (Exception e) {
        System.out.println("Exception in Thread Sleep : " + e);
    }
}

public String getTimeElapsed() {
    long elapsedTime = System.currentTimeMillis() - startTime;
    elapsedTime = elapsedTime / 1000;

    String seconds = Integer.toString((int) (elapsedTime % 60));
    String minutes = Integer.toString((int) ((elapsedTime % 3600) / 60));
    String hours = Integer.toString((int) (elapsedTime / 3600));

    if (seconds.length() < 2)
        seconds = "0" + seconds;

    if (minutes.length() < 2)
        minutes = "0" + minutes;

    if (hours.length() < 2)
        hours = "0" + hours;

    return minutes + ":" + seconds;
}

public static void main(String[] args) {
    new ElapsedTime();
}

}

I'm afraid there is no method to clear the console because Java is platform independant. I just insert 25 empty Lines so the last time disappears.

1 Comment

You're incorrect about not being able to clear the console. Password entry via the console depends on it! See java.sun.com/developer/technicalArticles/Security/pwordmask

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.