从 JFormattedTextField 到 LocalDate 的错误 - java.time.format.DateTimeParseException

问题描述

我有一个 jformattedtextfield,格式为 dd/MM/yyyy

我想以 dd/MM/yyyy 格式提取日期的日、月和年,时间日期“ES”(西班牙)。

我运行 JFrame,如果按 buttonjformattedtextfield 为空,为什么会出现以下错误 错误(见图):

enter image description here

我该如何解决我会展示我的代码...

代码

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import javax.swing.JButton;
import javax.swing.jformattedtextfield;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;

public class Ventana extends JFrame implements ActionListener {
    public JLabel label_date,label_calculo;
    public jformattedtextfield date; 
    public JButton button; 

    public Ventana() throws ParseException{
        super();
        configurarVentana();
        inicializarComponentes();
    }

    private void configurarVentana() {
        this.setTitle("Example");
        this.setSize(600,480);
        this.setLocationRelativeto(null);
        this.setLayout(null);
        this.setResizable(false);
        this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void inicializarComponentes() throws ParseException{
        label_date = new JLabel();
        label_calculo = new JLabel();
        date = new jformattedtextfield();
        button = new JButton();
        
        label_date.setText("Add date:");
        label_date.setBounds(50,50,100,25);
        date.setBounds(150,160,25);
        label_calculo.setText("Age: ");
        label_calculo.setBounds(50,90,300,25);
        button.setBounds(320,130,25);
        button.setText("Calculate age");
        
        this.add(label_date);
        this.add(date);
        this.add(button);
        this.add(label_calculo);
        
        button.addActionListener(this);
        
        //Format: jformattedtextfield dd-MM-yyyy
        date.setFormatterFactory(new DefaultFormatterFactory(new MaskFormatter("##/##/####")));
    }

    public void actionPerformed(ActionEvent e) {
        //JAVA 8.
        LocalDate ahora = LocalDate.Now();
        int dia_hoy = ahora.getDayOfMonth();
        int mes_hoy = ahora.getMonthValue();
        int ano_hoy = ahora.getYear();
        System.out.println(dia_hoy+"   "+mes_hoy+"   "+ano_hoy); 

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        LocalDate fechaNac = LocalDate.parse(date.getText(),fmt);
        int dia_nac = fechaNac.getDayOfMonth();
        int mes_nac = fechaNac.getMonthValue();
        int ano_nac = fechaNac.getYear();
        Period periodo = Period.between(fechaNac,ahora);

        if(date.getText().trim().isEmpty()){
            JOptionPane.showMessageDialog(null,"Date empty","AdminisTrador",JOptionPane.WARNING_MESSAGE);
        }else if(dia_nac<1 || dia_nac>31){
            JOptionPane.showMessageDialog(null,"Day incorrect",JOptionPane.WARNING_MESSAGE);
        }else if(mes_nac<1 || mes_nac>12){
            JOptionPane.showMessageDialog(null,"Month incorrect.",JOptionPane.WARNING_MESSAGE);
        }else if(ano_nac<1900 || ano_nac>ano_hoy){
            JOptionPane.showMessageDialog(null,"Year incorrect.",JOptionPane.WARNING_MESSAGE);
        }else{
            label_calculo.setText("You're "+String.valueOf(periodo.getYears())+" years old.");
        }
    }
    
    public static void main(String[] args) throws ParseException {
        Ventana V = new Ventana();
        V.setVisible(true);
    }

}

解决方法

您仍然没有发布正确的 MRE,因为您仍然不明白您正在尝试解决什么问题。

忘记您的应用程序,专注于问题。

这是一个合适的 MRE:

import java.time.*;
import java.time.format.*;


public class Main2
{
    public static void main(String[] args) throws Exception
    {
            String textFromTextField = "  /  /    "; // cause exception
//          String textFromTextField = "18/05/2021"; // works as expected

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
            LocalDate fechaNac = LocalDate.parse(textFromTextField,fmt);
            int dia_nac = fechaNac.getDayOfMonth();
            int mes_nac = fechaNac.getMonthValue();
            int ano_nac = fechaNac.getYear();

            System.out.println(dia_nac + " : " + mes_nac + " : " + ano_nac);
    }
}

它所做的只是尝试解析一个字符串。不需要 GUI 来解析字符串。

  1. 第一个字符串值尝试解析一个空字符串,这是您在格式化文本字段中未输入任何数据时得到的结果。它将生成您的异常。
  2. 第二个字符串试图演示输入有效数据时会发生什么。您获得了预期的输出。

下面是解决方案。您使用 try/catch 块来处理异常,然后执行与您的情况相关的任何处理:

import java.time.*;
import java.time.format.*;


public class Main2
{
    public static void main(String[] args) throws Exception
    {
        String textFromTextField = "  /  /    "; // cause exception
//      String textFromTextField = "18/05/2021"; // works as expected

        try
        {
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
            LocalDate fechaNac = LocalDate.parse(textFromTextField,fmt);
            int dia_nac = fechaNac.getDayOfMonth();
            int mes_nac = fechaNac.getMonthValue();
            int ano_nac = fechaNac.getYear();

            System.out.println(dia_nac + " : " + mes_nac + " : " + ano_nac);
        }
        catch (Exception e)
        {
            System.out.println("Invalid date format entered");
        };
    }
}

因此,解决问题的第一步是了解您要解决的问题。

通过简化问题,MRE更简单,论坛发帖更简单,解决方案更简单。