你可以帮我看一下如何在从datepicker中选择日期后自动计算年龄,以及何时将焦点从datepicker更改为年龄计算的年龄textfiel?
答案 0 :(得分:1)
FocusListener
会有所帮助,例如......
JXDatePicker dp = new JXDatePicker();
dp.getEditor().addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
// Calculate age
Date date = dp.getDate();
}
});
有关详细信息,请参阅How to Write a Focus Listener
年龄计算最好使用JodaTime或Java 8的新Time API
Date date = // Date from date picker
LocalDate ld = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//LocalDate ld = LocalDate.of(1972, Month.MARCH, 8);
Period p = Period.between(ld, LocalDate.now());
System.out.println(p.getYears());
System.out.println(p.getMonths());
System.out.println(p.getDays());
其中输出类似......
42
11
18
Date date = // Date from date picker
LocalDate ld = LocalDate.fromDateFields(date);
Period p = Period.fieldDifference(ld, LocalDate.now());
System.out.println(p.getYears());
System.out.println(p.getMonths());
System.out.println(p.getDays());