kleopatra already explained on how to set a Format
on the date picker. For this use-case, I would apply a combination of a CompositeFormat
and ParseAllFormat
instead of having a separate format for editing and regular mode to avoid changing the String
when you start editing (as you already noticed).
Composite format
The composite format, as the name suggests, is a composite implementation of the Format
class but only for the parsing. For the formatting, it uses one Format
. This allows the user to input his/her date in many forms, while it is formatted consistently by using one specific format to format.
You can obtain this behavior as well by writing one more sophisticated Format
. But in this case, it is easier to just use the formatting/parsing functionality offered by the SimpleDateFormat
class of the JDK.
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
/**
* <p>Composite form of {@link java.text.Format Format}. It uses multiple formats for parsing, and
* only one format for formatting.</p>
*
* <p>A possible use-case is the formatting of user input (e.g. in a {@code JFormattedTextField}).
* Multiple formats for parsing allows accepting multiple forms of user input without having to
* write a complicated format.</p>
*/
public class CompositeFormat extends Format {
private List<Format> fFormats = new ArrayList<>();
private Format fFormattingFormat;
/**
* Create a new
*/
public CompositeFormat() {
}
/**
* Add a format to this composite format
*
* @param aFormat The format to add
*/
public void addFormat( Format aFormat ) {
assertNotNull( aFormat, "You cannot add a null Format" );
if ( !( fFormats.contains( aFormat ) ) ) {
fFormats.add( aFormat );
}
}
/**
* Remove a format from this composite format
*
* @param aFormat The format to remove
*/
public void removeFormat( Format aFormat ) {
assertNotNull( aFormat, "You cannot remove a null Format" );
fFormats.remove( aFormat );
updateFormattingFormat();
}
/**
* Sets <code>aFormat</code> as the format which will be used for formatting the
* objects. The format will also be added to the list of available formats.
* @param aFormat The format which will be used for formatting
*/
public void setFormattingFormat( Format aFormat ){
assertNotNull( aFormat, "Formatting format may not be null" );
addFormat( aFormat );
fFormattingFormat = aFormat;
}
private void assertNotNull( Object aObjectToCheck, String aMessage ) {
if ( aObjectToCheck == null ) {
throw new NullPointerException( aMessage );
}
}
private void updateFormattingFormat(){
if ( !( fFormats.contains( fFormattingFormat ) ) ){
fFormattingFormat = null;
if ( !( fFormats.isEmpty() ) ){
fFormattingFormat = fFormats.iterator().next();
}
}
}
@Override
public StringBuffer format( Object obj, StringBuffer toAppendTo, FieldPosition pos ) {
assertNotNull( fFormattingFormat, "Set a formatting format before using this format" );
return fFormattingFormat.format( obj, toAppendTo, pos );
}
@Override
public Object parseObject( String source, ParsePosition pos ) {
if ( fFormats.isEmpty() ){
throw new UnsupportedOperationException( "Add at least one format before using this composite format" );
}
Format formatToUse = fFormats.iterator().next();
int maxIndex = pos.getIndex();
for ( Format format : fFormats ) {
ParsePosition tempPos = new ParsePosition( pos.getIndex() );
tempPos.setErrorIndex( pos.getErrorIndex() );
format.parseObject( source, tempPos );
if ( tempPos.getIndex() > maxIndex ){
maxIndex = tempPos.getIndex();
formatToUse = format;
if( maxIndex == source.length() ){
//found a format which parses the whole string
break;
}
}
}
return formatToUse.parseObject( source, pos );
}
}
ParseAllFormat
Typically for user input you want that the whole user input can be formatted/parsed to avoid that the user can input a String which is half-correct. The ParseAllFormat
is a decorator for a regular Format
which throws ParseException
s when only part of the String
can be parsed.
import java.text.AttributedCharacterIterator;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
/**
* <p>Decorator for a {@link Format Format} which only accepts values which can be completely parsed
* by the delegate format. If the value can only be partially parsed, the decorator will refuse to
* parse the value.</p>
*/
public class ParseAllFormat extends Format {
private final Format fDelegate;
/**
* Decorate <code>aDelegate</code> to make sure if parser everything or nothing
*
* @param aDelegate The delegate format
*/
public ParseAllFormat( Format aDelegate ) {
fDelegate = aDelegate;
}
@Override
public StringBuffer format( Object obj, StringBuffer toAppendTo, FieldPosition pos ) {
return fDelegate.format( obj, toAppendTo, pos );
}
@Override
public AttributedCharacterIterator formatToCharacterIterator( Object obj ) {
return fDelegate.formatToCharacterIterator( obj );
}
@Override
public Object parseObject( String source, ParsePosition pos ) {
int initialIndex = pos.getIndex();
Object result = fDelegate.parseObject( source, pos );
if ( result != null && pos.getIndex() < source.length() ) {
int errorIndex = pos.getIndex();
pos.setIndex( initialIndex );
pos.setErrorIndex( errorIndex );
return null;
}
return result;
}
@Override
public Object parseObject( String source ) throws ParseException {
//no need to delegate the call, super will call the parseObject( source, pos ) method
return super.parseObject( source );
}
}
The combination of these both classes allows for the following code
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class FormattingDemo {
private static Format createCompositeDateFormat(){
Format formattingFormat = new ParseAllFormat( new SimpleDateFormat( "dd.MM.yyyy" ) );
SimpleDateFormat shortFormat = new SimpleDateFormat( "dd.MM.yy" );
Format otherFormat = new ParseAllFormat( shortFormat );
CompositeFormat compositeFormat = new CompositeFormat();
compositeFormat.addFormat( otherFormat );
compositeFormat.addFormat( formattingFormat );
compositeFormat.setFormattingFormat( formattingFormat );
return compositeFormat;
}
public static void main( String[] args ) throws ParseException {
Format dateFormat = createCompositeDateFormat();
System.out.println( dateFormat.parseObject( "27.01.2010" ) );
System.out.println( dateFormat.parseObject( "27.01.10" ) );
System.out.println( dateFormat.parseObject( "27.01.2012" ) );
System.out.println(dateFormat.format( dateFormat.parseObject( "27.01.2010" ) ));
System.out.println(dateFormat.format( dateFormat.parseObject( "27.01.10" ) ));
System.out.println(dateFormat.format( dateFormat.parseObject( "27.01.2012" ) ));
}
}
resulting in the following output
Wed Jan 27 00:00:00 CET 2010
Wed Jan 27 00:00:00 CET 2010
Fri Jan 27 00:00:00 CET 2012
27.01.2010
27.01.2010
27.01.2012
Note that there is a small catch for which I did not found a decent solution. The order in which you add Format
instances to the CompositeFormat
is also the order in which they are evaluated for the parsing. In this case you need to add them in the correct order as even the new SimpleDateFormat( "dd.MM.yyyy" )
seems to accept the input string 27.01.10
and can parse the whole String
to a Date
object equivalent to 27.01.0010
.