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

从JFormattedTextField到LocalDate的错误-java.time.format.DateTimeParseException,java,localdate,jformattedtextfield,Java,Localdate,Jformattedtextfield,我有一个JFormattedTextField格式为dd/MM/yyyy 我想以dd/MM/yyyy格式提取日期的日、月和年,时间日期“ES”(西班牙) 我运行JFrame,如果我按下按钮,使JFormattedTextField为空,为什么会出现以下错误? 错误(请参见图): 我如何解决它?我将显示我的代码 代码: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text

我有一个
JFormattedTextField
格式为
dd/MM/yyyy

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

我运行
JFrame
,如果我按下
按钮,使
JFormattedTextField
为空,为什么会出现以下错误? 错误(请参见图):

我如何解决它?我将显示我的代码

代码:

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, 50, 160, 25);
        label_calculo.setText("Age: ");
        label_calculo.setBounds(50, 90, 300, 25);
        button.setBounds(320, 50, 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", "Administrador", JOptionPane.WARNING_MESSAGE);
        }else if(mes_nac<1 || mes_nac>12){
            JOptionPane.showMessageDialog(null, "Month incorrect.", "Administrador", JOptionPane.WARNING_MESSAGE);
        }else if(ano_nac<1900 || ano_nac>ano_hoy){
            JOptionPane.showMessageDialog(null, "Year incorrect.", "Administrador", 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);
    }

}
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.text.ParseException;
导入java.time.LocalDate;
导入java.time.Period;
导入java.time.format.DateTimeFormatter;
导入javax.swing.JButton;
导入javax.swing.JFormattedTextField;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JOptionPane;
导入javax.swing.text.DefaultFormatterFactory;
导入javax.swing.text.MaskFormatter;
公共类Ventana扩展JFrame实现ActionListener{
公共标签日期、标签计算;
公共JFormattedTextField日期;
公共按钮;
public Ventana()引发异常{
超级();
配置文塔纳();
Inicializarcomponents();
}
私有void configuraventana(){
本条。设定标题(“示例”);
这个.setSize(600480);
此.setLocationRelativeTo(空);
此.setLayout(null);
此参数为.setresizeable(false);
此.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void inicializarComponentes()引发ParseException异常{
label_date=new JLabel();
label_calculo=新的JLabel();
日期=新JFormattedTextField();
按钮=新的JButton();
label_date.setText(“添加日期:”);
标签日期(50,50,100,25);
日期.立根(150,50,160,25);
标签_calculo.setText(“年龄:”);
标签(50、90、300、25);
按钮.立根(320,50,130,25);
按钮.setText(“计算年龄”);
添加(标签日期);
本条增补(日期);
这个。添加(按钮);
此项。添加(标签_calculo);
addActionListener(这个);
//格式:JFormattedTextField dd MM yyyy
date.setFormatterFactory(新的DefaultFormatterFactory(新的MaskFormatter(“##/##/##/##”));
}
已执行的公共无效操作(操作事件e){
//爪哇8。
LocalDate ahora=LocalDate.now();
int dia_hoy=ahora.getDayOfMonth();
int mes_hoy=ahora.getMonthValue();
int ano_hoy=ahora.getYear();
系统输出打印LN(直径+最小值+最小值+最小值);
DateTimeFormatter fmt=模式的DateTimeFormatter.of(“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=期间(fechaNac,ahora);
if(date.getText().trim().isEmpty()){
showMessageDialog(null,“日期为空”,“管理员”,JOptionPane.WARNING_消息);
}否则,如果(直径为31){
JOptionPane.showMessageDialog(空,“日期不正确”,“管理员”,JOptionPane.WARNING_消息);
}其他条件(mes_nac12){
JOptionPane.showMessageDialog(null,“月份不正确”,“管理员”,JOptionPane.WARNING_消息);
}否则如果(ano_nacano_hoy){
JOptionPane.showMessageDialog(null,“年份不正确”,“管理员”,JOptionPane.WARNING_消息);
}否则{
label_calculo.setText(“您是”+String.valueOf(periodo.getYears())+“岁”);
}
}
公共静态void main(字符串[]args)引发异常{
文塔纳V=新文塔纳();
V.setVisible(真);
}
}

您仍然没有发布正确的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来解析字符串

  • 第一个字符串值尝试解析一个空字符串,当您没有在格式化文本字段中键入任何数据时,将得到该空字符串。它将生成您的异常
  • 第二个字符串试图演示输入有效数据时发生的情况。您将获得预期的输出
  • 下面是解决方案。您使用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更简单,论坛中的帖子也更简单,解决方案也更简单。

    看起来你从文本字段中得到了“/”。所有日期字段都在哪里blank@Jens谢谢你的帮助,但是。。。如果我运行JFrame,但没有填充JFormattedTextField,则会出现此错误。为什么?因为它试图在这一行解析它
    LocalDate fechaNac=LocalDate.parse(formattedtextfield.getText(),fmt)@Jens So。。我怎么能修好它<代码>如果(formattedtextfield.getText().trim().isEmpty()){
    这不起作用。请检查字符串中是否有除blan和斜杠以外的其他字符,以及是否包含这些字符,或者捕获异常并返回如果没有有效日期则显示错误消息谢谢您的回答。