JFormattedTextfield: Display double values as time format
Dez.11, 2009 von Christophe Denis in
Java
Here you can find a Formatter-Implementation which is able to format double values in JFormattedTextfield as time format like “01:30″ and vice versa, i.e. needed for duration inputs. Furthermore you don’t need to input the :-separator, “0130″ will be automatically translated to “01:30″ . The formatter is also able to allow ‘native’ double inputs like “1.5″ or even “1,5″.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | import java.text.ParseException; import javax.swing.text.DefaultFormatter; /** * <p> * This format converts a double value into a time format like 10:30 and vice versa. * </p> * <p> * Furthermore it checks if the input string<br /> * a) can be assumed as time format without :-separator ("1030" -> 10:30)<br /> * or<br /> * b) is parseble as 'native' double value (like "0.5" = 00:30). It allows also inputs like "1,5". * </p> * * @author denis[@]ibs-aachen.de */ public class DoubleTimeFormatter extends DefaultFormatter { private static final long serialVersionUID = -60169060463898543L; @Override public Object stringToValue(String string) throws ParseException { string = string.replace(',', '.'); if (string.length() == 4) { try { Integer.parseInt(string); // check that it does only contain numbers String newString = string.substring(0, 2); newString += ":"; newString += string.substring(2, 4); string = newString; } catch (NumberFormatException e) { // not possible/necessary to manipulate string to time-format } } Double d; try { d = Double.parseDouble(string); return d; } catch (NumberFormatException e) { // continue trying to parse time-format } d = new Double(0.); if (string.contains(":")) { String[] parts = string.split("[:]"); if (parts.length > 0) { d += ("".equals(parts[0].trim()) ? 0 : Integer.parseInt(parts[0].trim())); } if (parts.length == 2) { d += ("".equals(parts[1].trim()) ? 0 : Integer.parseInt(parts[1].trim()) / 60.); } } else { d += ("".equals(string.trim()) ? 0 : Integer.parseInt(string.trim())); } return d; } @Override public String valueToString(Object value) throws ParseException { if (value == null) { return ""; } StringBuffer toAppendTo = new StringBuffer(); try { Double d = (Double) value; int n = d.intValue(); toAppendTo.append(String.format("%02d:%02d", n, (int) ((d - n) * 60))); } catch (ClassCastException e) { throw new NumberFormatException("Need double value!"); } return toAppendTo.toString(); } } |
Add it to your textfield like this:
1 | JFormattedTextField textfield = new JFormattedTextField(new DoubleTimeFormatter()); |
Feedback appreciated ;o)

Leave a Reply