Java - Tipear con Date Picker

 
Vista:
Imágen de perfil de Francisco
Val: 85
Ha aumentado su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

Tipear con Date Picker

Publicado por Francisco (56 intervenciones) el 21/10/2018 23:51:09
Buenas, estoy hacíendo un ejercicio con Date Picker en java fx, pero no me sale.


He buscado videos pero realmente no explican tan bien como ustedes.

Es lo siguiente, tengo la clase Persona. Pero simplemente les mando el código.



package tpn6.controladores.direcciones.modelos;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import java.sql.Date;
import java.time.LocalDate;
 
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import tpn6.controladores.direcciones.util.LocalDateAdapter;
 
 
public class Persona {
 
    private final IntegerProperty id;
    private final StringProperty nombre;
    private final StringProperty apellido;
    private final StringProperty direccion;
    private final IntegerProperty codigoPostal;
    private final StringProperty ciudad;
    private final ObjectProperty<LocalDate> fechaDeNacimiento;
 
 
    /**
     * Default constructor.
     */
    public Persona() {
        this(null, null);
    }
 
    /**
     * Constructor with some initial data.
     * 
     * @param firstName
     * @param lastName
     */
    public Persona(String nombre, String apellido) {
        this.id = new SimpleIntegerProperty(1000);
        this.nombre = new SimpleStringProperty(nombre);
        this.apellido = new SimpleStringProperty(apellido);
 
        // Some initial dummy data, just for convenient testing.
        this.direccion = new SimpleStringProperty("");
        this.codigoPostal = new SimpleIntegerProperty(1234);
        this.ciudad = new SimpleStringProperty("");
        this.fechaDeNacimiento = new SimpleObjectProperty<LocalDate>(LocalDate.of(1999, 2, 21));
    }
 
    public IntegerProperty idProperty() {
        return id;
    }
    public int getId(){
        return id.get();
    }
    public void setId(int id){
        this.id.set(id);
    }
    public String getFirstName() {
        return nombre.get();
    }
 
    public void setFirstName(String nombre) {
        this.nombre.set(nombre);
    }
 
    public StringProperty firstNameProperty() {
        return nombre;
    }
 
    public String getLastName() {
        return apellido.get();
    }
 
    public void setLastName(String apellido) {
        this.apellido.set(apellido);
    }
 
    public StringProperty lastNameProperty() {
        return apellido;
    }
 
    public String getStreet() {
        return direccion.get();
    }
 
    public void setStreet(String direccion) {
        this.direccion.set(direccion);
    }
 
    public StringProperty streetProperty() {
        return direccion;
    }
 
    public int getPostalCode() {
        return codigoPostal.get();
    }
 
    public void setPostalCode(int codigoPostal) {
        this.codigoPostal.set(codigoPostal);
    }
 
    public IntegerProperty postalCodeProperty() {
        return codigoPostal;
    }
 
    public String getCity() {
        return ciudad.get();
    }
 
    public void setCity(String ciudad) {
        this.ciudad.set(ciudad);
    }
 
    public StringProperty cityProperty() {
        return ciudad;
    }
@XmlJavaTypeAdapter(LocalDateAdapter.class)
    public LocalDate getBirthday() {
        return fechaDeNacimiento.get();
    }
 
    public void setBirthday(LocalDate fechaDeNacimiento) {
      this.fechaDeNacimiento.set(fechaDeNacimiento);
    }
 
    public ObjectProperty<LocalDate> birthdayProperty() {
        return fechaDeNacimiento;
    }
 
 
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package tpn6.controladores.direcciones.util;
 
 
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import javafx.fxml.FXML;
import javafx.scene.control.DatePicker;
 
public class FechaUtil {
 
    @FXML
    DatePicker fecha;
     /** The date pattern that is used for conversion. Change as you wish. */
    private static final String DATE_PATTERN = "dd.MM.yyyy";
 
    /** The date formatter. */
    private static final DateTimeFormatter DATE_FORMATTER =
            DateTimeFormatter.ofPattern(DATE_PATTERN);
 
    /**
     * Returns the given date as a well formatted String. The above defined 
     * {@link DateUtil#DATE_PATTERN} is used.
     * 
     * @param date the date to be returned as a string
     * @return formatted string
     */
    public static String format(LocalDate date) {
        if (date == null) {
            return null;
        }
        return DATE_FORMATTER.format(date);
    }
 
    /**
     * Converts a String in the format of the defined {@link DateUtil#DATE_PATTERN} 
     * to a {@link LocalDate} object.
     * 
     * Returns null if the String could not be converted.
     * 
     * @param dateString the date as String
     * @return the date object or null if it could not be converted
     */
 
    public static LocalDate parse(String dateString) {
        try {
            return DATE_FORMATTER.parse(dateString, LocalDate::from);
        } catch (DateTimeParseException e) {
            return null;
        }
    }
 
 
 
    /**
     * Checks the String whether it is a valid date.
     * 
     * @param dateString
     * @return true if the String is a valid date
     */
    public static boolean validDate(String dateString) {
        // Try to parse the String.
        return FechaUtil.parse(dateString) != null;
    }
 
}





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package tpn6.controladores.direcciones.util;
 
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import javafx.fxml.FXML;
import javafx.scene.control.DatePicker;
 
public class FechaUtilBaseDatos {
 
 
     @FXML
    DatePicker fecha;
     /** The date pattern that is used for conversion. Change as you wish. */
    private static final String DATE_PATTERN = "yyyy-MM-dd";
 
    /** The date formatter. */
    private static final DateTimeFormatter DATE_FORMATTER =
            DateTimeFormatter.ofPattern(DATE_PATTERN);
 
    /**
     * Returns the given date as a well formatted String. The above defined 
     * {@link DateUtil#DATE_PATTERN} is used.
     * 
     * @param date the date to be returned as a string
     * @return formatted string
     */
    public static String format(LocalDate date) {
        if (date == null) {
            return null;
        }
        return DATE_FORMATTER.format(date);
    }
 
    /**
     * Converts a String in the format of the defined {@link DateUtil#DATE_PATTERN} 
     * to a {@link LocalDate} object.
     * 
     * Returns null if the String could not be converted.
     * 
     * @param dateString the date as String
     * @return the date object or null if it could not be converted
     */
 
    public static LocalDate parse(String dateString) {
        try {
            return DATE_FORMATTER.parse(dateString, LocalDate::from);
        } catch (DateTimeParseException e) {
            return null;
        }
    }
 
 
 
    /**
     * Checks the String whether it is a valid date.
     * 
     * @param dateString
     * @return true if the String is a valid date
     */
    public static boolean validDate(String dateString) {
        // Try to parse the String.
        return FechaUtilBaseDatos.parse(dateString) != null;
    }
}


Ahora les mando dónde esta el error. Está en esta clase, cuando ingreso un valor de DatePicker y le pongo en guardar se me abre un Alert diciéndome que tipee bien los campos. Yo lo que quiero es que al ingresar un valor de tipo DatePicker en formato "dd.MM.yyyy" me lo pase a "yyyy-MM-dd" y se logre guardar correctamente sin que aparezca el mensaje de tipear bien los campos. Aca esta el codigo donde esta el error en el controlador de ingresar personas.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
@FXML
    private DatePicker birthdayField;
 
public void setPerson(Persona person) {
    this.person = person;
 
    idField.setText(Integer.toString(person.getId()));
    firstNameField.setText(person.getFirstName());
    lastNameField.setText(person.getLastName());
    streetField.setText(person.getStreet());
    postalCodeField.setText(Integer.toString(person.getPostalCode()));
    cityField.setText(person.getCity());
    //    birthdayField.setText(FechaUtil.format(person.getBirthday()));
    //   birthdayField.setPromptText("dd.mm.yyyy");
 
     birthdayField.setValue(person.getBirthday());
     birthdayField.setPromptText("dd.mm.yyyy");
}
 
 
 
 
 
 @FXML
    private void handleOk() throws ParseException {
        if (isInputValid()) {
 
            ControladorDePersonas controladorPersonas = new ControladorDePersonas();
 
            person.setId(Integer.parseInt(idField.getText()));
            person.setFirstName(firstNameField.getText());
            person.setLastName(lastNameField.getText());
            person.setStreet(streetField.getText());
            person.setPostalCode(Integer.parseInt(postalCodeField.getText()));
            person.setCity(cityField.getText());
           // person.setBirthday(FechaUtil.parse(birthdayField.getText()));
 
       //     person.setBirthday(FechaUtilBaseDatos.parse(FechaUtil.parse(birthdayField.getText()).toString()));
 
           person.setBirthday(FechaUtilBaseDatos.parse(FechaUtil.parse(birthdayField.getValue().toString()).toString()));
            try {
                controladorPersonas.registrarPersona(person);
            } catch (ParseException ex) {
                Logger.getLogger(PersonNewDialogController.class.getName()).log(Level.SEVERE, null, ex);
            }
 
            okClicked = true;
            escenarioDialogo.close();
        }
    }
 
 
 
 
 
private boolean isInputValid() {
    String errorMessage = "";
 
    if(birthdayField.getValue() == null){
        errorMessage += "No valid birthday!\n";
    }else{
        if(!FechaUtil.validDate(birthdayField.getValue().toString())){
            errorMessage += "No valid birthday. Use the format dd.mm.yyyy!\n";
        }
    }
    if (errorMessage.length() == 0) {
        return true;
    } else {
        // Show the error message.
 
        Alert alert = new Alert(Alert.AlertType.ERROR);
 
        alert.setTitle("Inválido");
        alert.setHeaderText("tipear bien los campos.");
        alert.showAndWait();
 
        return false;
    }
}


El ultimo codigo que les mande no esta completo justamente para que vean ahí en que me equivoqué.


Yo lo único que quiero en base a lo que les mande es que pueda ingresar un DatePicker en formato "dd.MM.yyyy" y se me convierta a "yyyy-MM-dddd" que este ultimo es el formato con el que operan las bases de datos de mysql y que lo pueda ingresar bien.


Se los agradecería muchísimo
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder