Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jXDatePicker with maskFormatter?

I would like to use a jxdatepicker with maskFormatter. I tried

MaskFormatter maskFormatter = new MaskFormatter ("##/##/####");
JFormattedTextField field=new JFormattedTextField (maskFormatter);
jXDatePicker.setEditor (field);

and

MaskFormatter maskFormatter = new MaskFormatter ("##/##/####");
maskFormatter.install (jXDatePicker.getEditor ());

neither the first nor the second solution worked

PS: A JFormattedTextField work fine with MaskFormatter AND jXDatePicker work fine with a simple JFormattedTextField

like image 806
Billydan Avatar asked Apr 26 '16 08:04

Billydan


1 Answers

This is an old question, but seems to be still active, so here is how we implemented the functionality some time ago (swingx-all-1.6.5-1.jar):

1) Create a wrapper class for MaskFormatter

public class Wrapper extends MaskFormatter {

private final static String DD_MM_YYY = "dd/MM/yyyy";

public Wrapper(String string) throws ParseException {
    super(string);

}

@Override
public Object stringToValue(String value) throws ParseException {

    SimpleDateFormat format = new SimpleDateFormat(DD_MM_YYY);
    Date parsed = format.parse(value);
    return parsed;

}

public String valueToString(Object value) throws ParseException {
    if (value != null) {
        SimpleDateFormat format = new SimpleDateFormat(DD_MM_YYY);
        String formated = format.format((Date) value);
        return super.valueToString(formated);
    } else {
        return super.valueToString(value);
    }

  }

}


2) Add the wrapped Formatter to the JFormattedTextField and set it on the JXDatePicker

MaskFormatter maskFormatter;
JXDatePicker datePicker = new JXDatePicker();
try {
        maskFormatter = new Wrapper("##/##/####");
        JFormattedTextField field = new JFormattedTextField(maskFormatter);
        datePicker.setEditor(field);
} catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
}
somePanel.add(datePicker);

The wrapper class basically does the formatting, since trying to set a DateFormat on the JXDatePicker led to various ParseException.

like image 151
briadeus Avatar answered Sep 17 '22 13:09

briadeus