焦点变化后自动计算年龄

时间:2015-02-26 04:06:32

标签: java netbeans

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

Sample Form Here

1 个答案:

答案 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

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());