01: /*
02: * Copyright 2005 Sun Microsystems, Inc., 4150 Network Circle,
03: * Santa Clara, California 95054, U.S.A. All rights reserved.
04: *
05: * This library is free software; you can redistribute it and/or
06: * modify it under the terms of the GNU Lesser General Public
07: * License as published by the Free Software Foundation; either
08: * version 2.1 of the License, or (at your option) any later version.
09: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library; if not, write to the Free Software
17: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18: */
19: package org.jdesktop.swingx;
20:
21: import javax.swing.JFormattedTextField;
22: import javax.swing.UIManager;
23: import java.text.DateFormat;
24: import java.text.SimpleDateFormat;
25: import java.text.ParseException;
26:
27: /**
28: * Default formatter for the JXDatePicker component. This factory
29: * creates and returns a formatter that can handle a variety of date
30: * formats.
31: *
32: * @author Joshua Outwater
33: */
34: public class JXDatePickerFormatter extends
35: JFormattedTextField.AbstractFormatter {
36: private DateFormat _formats[] = null;
37:
38: public JXDatePickerFormatter() {
39: _formats = new DateFormat[3];
40: _formats[0] = new SimpleDateFormat(UIManager
41: .getString("JXDatePicker.longFormat"));
42: _formats[1] = new SimpleDateFormat(UIManager
43: .getString("JXDatePicker.mediumFormat"));
44: _formats[2] = new SimpleDateFormat(UIManager
45: .getString("JXDatePicker.shortFormat"));
46: }
47:
48: public JXDatePickerFormatter(DateFormat formats[]) {
49: _formats = formats;
50: }
51:
52: public DateFormat[] getFormats() {
53: return _formats;
54: }
55:
56: /**
57: * {@inheritDoc}
58: */
59: public Object stringToValue(String text) throws ParseException {
60: Object result = null;
61: ParseException pex = null;
62:
63: if (text == null || text.trim().length() == 0) {
64: return null;
65: }
66:
67: // If the current formatter did not work loop through the other
68: // formatters and see if any of them can parse the string passed
69: // in.
70: for (DateFormat _format : _formats) {
71: try {
72: result = (_format).parse(text);
73: pex = null;
74: break;
75: } catch (ParseException ex) {
76: pex = ex;
77: }
78: }
79:
80: if (pex != null) {
81: throw pex;
82: }
83:
84: return result;
85: }
86:
87: /**
88: * {@inheritDoc}
89: */
90: public String valueToString(Object value) throws ParseException {
91: if (value != null) {
92: return _formats[0].format(value);
93: }
94: return null;
95: }
96: }
|