![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e996. Creating a Text Field to Display and Edit a DateThis example uses aJFormattedTextField to allow the display and
editing of a date. By default, when the component loses the focus and
the modified value is a valid date, the modified value is
saved. Otherwise, if the modified value is not a valid date, the
modified value is discarded and the old value is displayed.
// Support a date in the MEDIUM format in the current locale; // see e322 Formatting and Parsing a Date Using Default Formats. // For Locale.ENGLISH, the format would be Feb 8, 2002. JFormattedTextField tft1 = new JFormattedTextField(new Date()); // Support a date in the SHORT format using the current locale. // For Locale.ENGLISH, the format would be 2/8/02. JFormattedTextField tft2 = new JFormattedTextField(DateFormat.getDateInstance(DateFormat.SHORT)); tft2.setValue(new Date()); // Support a date with the custom format: 2002-8-2 JFormattedTextField tft3 = new JFormattedTextField(new SimpleDateFormat("yyyy-M-d")); tft3.setValue(new Date()); // See also e320 Formatting a Date Using a Custom Format // Retrieve the date from the text field Date date = (Date)tft3.getValue();The following example demonstrates how to dynamically change the format: // Change the format to: 2/8/2002 DateFormatter fmt = (DateFormatter)tft3.getFormatter(); fmt.setFormat(new SimpleDateFormat("d/M/yyyy")); // Reformat the display tft3.setValue(tft3.getValue());
e997. Creating a Text Field to Display and Edit a Phone Number
© 2002 Addison-Wesley. |