Frage

I have the estimated time the it would take for a particular task in minutes in a float. How can I put this in a JFormattedTextField in the format of HH:mm:ss?

War es hilfreich?

Lösung

JFormattedTextField accepts a Format object - you could thus pass a DateFormat that you get by calling DateFormat#getTimeInstance(). You might also use a SimpleDateFormat with HH:mm:ss as the format string.

See also: http://download.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html#format


If you're not restricted to using a JFormattedTextField, you might also consider doing your own formatting using the TimeUnit class, available since Java 1.5, as shown in this answer: How to convert Milliseconds to "X mins, x seconds" in Java?

Andere Tipps

For a float < 1440 you can get around with Calendar and DateFormat.

float minutes = 100.5f; // 1:40:30

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.add(Calendar.MINUTE, (int) minutes);
c.add(Calendar.SECOND, (int) ((minutes % (int) minutes) * 60));
final Date date = c.getTime();

Format timeFormat = new SimpleDateFormat("HH:mm:ss");
JFormattedTextField input = new JFormattedTextField(timeFormat);
input.setValue(date);

But be warned that if your float is greater than or equal to 1440 (24 hours) the Calendar method will just forward a day and you will not get the expected results.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top