java – 焦点变化后自动计算年龄

你可以帮我看看如何在从datepicker中选择日期后自动计算年龄,以及何时焦点从datepicker更改为年龄计算的年龄textfiel?

Sample Form Here

解决方法:

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完成

Java 8

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());
上一篇:从netbeans运行java applet?


下一篇:JavaFX8 – 找不到sun.util.logging.PlatformLogger在NetBeans 8中的异常