本文介绍了焦点改变后自动计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能否帮助我了解如何在从日期选择器中选择日期后自动计算年龄以及当焦点从日期选择器更改为年龄文本字段时如何计算年龄?

Can you please help me on how to Automatically calculate age after selecting date from datepicker and when focus is changed from datepicker to age textfiel the age calculates?

此处的表格示例

推荐答案

FocusListener 会有所帮助,例如...

A FocusListener will help, for example...

    JXDatePicker dp = new JXDatePicker();
    dp.getEditor().addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            // Calculate age
            Date date = dp.getDate();
        }
    });

有关详细信息,请参阅如何编写焦点侦听器

年龄计算最好使用 JodaTime 或 Java 8 的新时间 API

The age calculation is best done using either JodaTime or Java 8's new 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());

这篇关于焦点改变后自动计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 12:58