-3

I have a JFormattedTextField in which the format is dd/MM/yyyy

I want to extract the day, month and year of a date, in dd/MM/yyyy format, time date "ES" (Spain).

I run the JFrame, and if I press button, having the JFormattedTextField empty, why do I have the following error? The error (see image):

enter image description here

How can I resolve it? I'll show my code...

Code:

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

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
SrCantabri
  • 37
  • 5
  • 1
    looks like you get ` / / ` from the textfield. where all date fields ar blank – Jens May 18 '21 at 11:37
  • @Jens Thanks for the help but... if i run the JFrame, without fill JFormattedTextField, i have this error. Why? – SrCantabri May 18 '21 at 12:26
  • Because it tried to parse it at this line `LocalDate fechaNac = LocalDate.parse(formattedtextfield.getText(), fmt);` – Jens May 18 '21 at 12:55
  • @Jens So.. how i can fix it? `if(formattedtextfield.getText().trim().isEmpty()){` this doesnt work. – SrCantabri May 18 '21 at 13:39
  • check if there are other characters than blan and slash in the string and than partse it or not, or catch the exception and return show an error message if there is no valid date – Jens May 18 '21 at 13:56
  • @Jens I think I did. Look at the `button_edadActionPerformed()` – SrCantabri May 18 '21 at 14:19
  • (1-) This is NOT an [mre]. How can we copy/paste/compile and test? We don't know what the initComponents() method does. For your problem all you need is a JFrame, a JFormattedTextField and a JButton. Get this basic code working then fix your application. Learn how to create an MRE. You have been given a link on this in your previous question and have been give an complete example of an MRE in that question. – camickr May 18 '21 at 14:37
  • -3 Why is the question voted negative if I have included an explanation, the image of the error and the code tried? So all forum questions should include MRE, right? I don't know how to include a demonstrable MRE example, so I haven't done it yet. The link does not indicate the steps to do so in Java. – SrCantabri May 18 '21 at 15:09
  • An MRE is simply code that we can copy/paste/compile and test. Does the code you posted compile? No, because the initComponents() method is not defined. Will the code execute AFTER all the compile bugs are fixed. No, because there is no main() method. Again, the point of the MRE is NOT to just paste your application. We are only interested in the code directly related to the question asked and the code posted will compile and execute so we can see the behaviour of the described problem. You were given an example of an MRE in your last question!!! – camickr May 18 '21 at 15:21
  • @camickr Now? See the edit. Code for compile and test. – SrCantabri May 18 '21 at 16:31
  • Provide details about the question so that we can copy paste and reproduce the same. it will help us to respond faster and accurate. – Pashyant Srivastava May 18 '21 at 16:37
  • @PashyantSrivastava Read the explanation for the problem. – SrCantabri May 18 '21 at 16:45
  • It seems that my question is uncomfortable, so many negative votes when I have put an explanation, the code programmed and available to compile and test. – SrCantabri May 18 '21 at 16:46
  • How is that an MRE? 1) it doesn't compile because there are no import statements 2) When I fixed the missing import statements I get an `UnsupportedOperationException`, not a DateTimeParseException. Just because it compiles doesn't make it an MRE we also need to be able to test to see the same results. – camickr May 18 '21 at 17:05
  • @camickr Its my code. Look at the imagen in the question. Error: `java.time.format.DateTimeParseException`. I edited with import statements, ready – SrCantabri May 18 '21 at 17:12
  • @camickr "we also need to be able to test to see the same results.". Look at the image and you'll see my results and my test. – SrCantabri May 18 '21 at 17:15
  • Copy all the code because it should compile and be able to be tested without any problem. – SrCantabri May 18 '21 at 17:39

1 Answers1

1

You still haven't posted proper MRE, because you still don't understand what problem you are attempting to fix.

Forget about your application and concentrate on the problem.

Here is a proper 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);
    }
}

All it does is attempt to parse a String. There is no need for a GUI to parse a String.

  1. The first string value attempts to parse an empty string which is what you get when you don't type any data into your formatted text field. It will generate your Exception.
  2. The second string attempts to demonstrate what happens when a valid data is entered. You get the expected output.

Below is the solution. You use a try/catch block to handle the Exception and then do whatever processing is relevant in your case:

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");
        };
    }
}

So the first step in solving a problem is knowing what problem you are attempting to solve.

By simplifying the problem, the MRE is simpler and the posting in the forum is simpler and the solution is simpler.

camickr
  • 321,443
  • 19
  • 166
  • 288