简体   繁体   中英

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

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 .

Personally I'm not very skilled in Java but after checking some docs quickly. I think setEditor is not the way to go. With maskFormatter.install you seem to go into the right direction. Something like this might help you out:

JXDatePicker picker = new JXDatePicker();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
picker.setFormats(format);

Selective source: JXDatePicker using SimpleDateFormat to format dd.MM.yy to dd.MM.yyyy with current century

Or check out this: https://stackoverflow.com/a/9036979/4820655

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM