手动输入日期时出错
线程“AWT-EventQueue-0”中的异常 java.lang.ClassCastException:java.util.Date 无法转换为 java.util.Calendar
如何改进代码以便手动输入和使用下拉日历成为可能?
public class WordWorker {
public static void main(String[] args) {
Locale locale=new Locale("ru","RU");
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(300,300);
UtilDateModel model=new UtilDateModel();
Properties p=new Properties();
p.put("text.today","Today");
p.put("text.month","Month");
p.put("text.year","Year");
JDatePanelImpl datePanel=new JDatePanelImpl(model,p);
JDatePickerImpl datePicker=new JDatePickerImpl(datePanel,new DateLabelFormatter());
datePicker.setTextEditable(true);
frame.add(datePicker,"Center");
JButton jButton=new JButton("Кнопка");
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(datePicker.getModel().getDay());
System.out.println(datePicker.getModel().getMonth()+1);
System.out.println(datePicker.getModel().getYear());
System.out.println(datePicker.getModel().getValue());
}
});
frame.add(jButton,"South");
frame.setVisible(true);
}
private static class DateLabelFormatter extends JFormattedTextField.AbstractFormatter
{
private String datePattern="dd.MM.yyyy";
private SimpleDateFormat dateFormatter=new SimpleDateFormat(datePattern);
@Override
public Object stringToValue(String text) throws ParseException {
return dateFormatter.parseObject(text);
}
@Override
public String valueToString(Object value) throws ParseException {
if (value!=null)
{
Calendar cal= (Calendar) value;
return dateFormatter.format(cal.getTime());
}
return "";
}
}
}
此方法中的解决方案: