1 7 package org.jdesktop.swing.calendar; 8 9 import java.text.ParseException ; 10 import java.text.SimpleDateFormat ; 11 import javax.swing.JFormattedTextField ; 12 import javax.swing.JFormattedTextField.AbstractFormatter; 13 import javax.swing.JFormattedTextField.AbstractFormatterFactory; 14 import javax.swing.UIManager ; 15 16 22 public class JXDatePickerFormatterFactory extends AbstractFormatterFactory { 23 24 protected AbstractFormatter formatter = null; 25 26 29 public AbstractFormatter getFormatter(JFormattedTextField ftf) { 30 if (formatter == null) { 31 formatter = new JXDatePickerFormatter(); 32 } 33 return formatter; 34 } 35 36 56 private class JXDatePickerFormatter extends 57 JFormattedTextField.AbstractFormatter { 58 private SimpleDateFormat _formats[] = null; 59 private int _formatIndex = 0; 60 61 public JXDatePickerFormatter() { 62 _formats = new SimpleDateFormat [3]; 63 String format = UIManager.getString("JXDatePicker.longFormat"); 64 if (format == null) { 65 format = "EEE MM/dd/yyyy"; 66 } 67 _formats[0] = new SimpleDateFormat (format); 68 69 format = UIManager.getString("JXDatePicker.mediumFormat"); 70 if (format == null) { 71 format = "MM/dd/yyyy"; 72 } 73 _formats[1] = new SimpleDateFormat (format); 74 75 format = UIManager.getString("JXDatePicker.shortFormat"); 76 if (format == null) { 77 format = "MM/dd"; 78 } 79 _formats[2] = new SimpleDateFormat (format); 80 } 81 82 85 public Object stringToValue(String text) throws ParseException { 86 Object result = null; 87 ParseException pex = null; 88 89 if (text == null || text.trim().length() == 0) { 90 return null; 91 } 92 93 if (result == null) { 97 for (int i = 0; i < _formats.length; i++) { 98 try { 99 result = ((SimpleDateFormat )_formats[i]).parse(text); 100 101 _formatIndex = i; 104 pex = null; 105 break; 106 } catch (ParseException ex) { 107 pex = ex; 108 } 109 } 110 } 111 112 if (pex != null) { 113 throw pex; 114 } 115 116 return result; 117 } 118 119 122 public String valueToString(Object value) throws ParseException { 123 if (value != null) { 124 return _formats[_formatIndex].format(value); 125 } 126 return null; 127 } 128 } 129 } 130 | Popular Tags |