Biscuit128
Biscuit128

Reputation: 5398

Display the value of swing timer

Currently I am printing my values for my swing worker timer in a label

.setText(days + " Days :" + hours + " Hours :" +  mins + " Minutes : " + seconds + " Seconds elapsed")

I was wondering if it were possible to format this in a slightly neater way?

Upvotes: 1

Views: 1361

Answers (3)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

I've got a program that I'm working on now that uses String.format(...) and a format String for this:

// in the constants section
private static final String DISPLAY_FORMAT_STR = "%02d:%02d:%02d:%01d";   


private void showTimeLeft() {
  int oldMin = min;
  hours = (int) (deltaTime / (MS_PER_SEC * SEC_PER_MIN * MIN_PER_HR));
  min = (int) (deltaTime / (MS_PER_SEC * SEC_PER_MIN) % MIN_PER_HR);
  sec = (int) (deltaTime / (MS_PER_SEC) % SEC_PER_MIN);
  msec = (int) (deltaTime % MS_PER_SEC);

  String displayString = String.format(DISPLAY_FORMAT_STR, hours, min, sec,
        msec / 100);
  displayField.setText(displayString);

  // ... etc...

Otherwise if you're dealing with a Date object (I'm not), you could use a SimpleDateFormat object to better format your output.

Upvotes: 2

mKorbel
mKorbel

Reputation: 109813

One of ways, how do you can calculating elapsed time

long start = System.currentTimeMillis();

// some code executed 

long end = System.currentTimeMillis();
long elapsed = end - start;
long seconds = elapsed / 1000;

rest for calculating days / hours / minutes / seconds

Upvotes: 1

DNA
DNA

Reputation: 42597

How about String.format()?

http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax

Upvotes: 1

Related Questions