这是一个老问题,但似乎仍然处于活动状态,因此以下是我们前段时间如何实现该功能():
1)创建一个包装器类swingx-all-1.6.5-1.jar
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) 将包装的格式化程序添加到 中,并将其设置在JFormattedTextField
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);
包装类基本上做格式化,因为试图在导致各种.DateFormat
JXDatePicker
ParseException