I have:
- SQL Server 2017
- I have
jcalendar-1.4
added to my project - I have
import java.sql.Date;
in my class. - I have the column
fechaNacimiento
typeDATE
in my database.
To obtain the information from the database and put together the model
of JTable
use:
String [] titulosColumnas = {"ID", "Nombre", "FechaNacimiento"};
ArrayList<Object[]> registros = new ArrayList<Object[]>();
while (rs.next()) {
registros.add(new Object[] {
rs.getInt("id_director"),
rs.getString("nombre"),
// Aquí paso la información obtenida a String, porque JTable solo permite String's, cierto?.
rs.getDate("fechaNacimiento").toString()
});
}
model = new DefaultTableModel(registros.toArray(new Object[0][]), titulosColumnas);
My resulting JTable:
At this moment, when I click on a row of the JTable, I receive the error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.util.Date can not be cast to java.sql.Date at views.Director_View $ 7.mouseClicked (Vista_director.java:272)
JTable code when you click:
table = new JTable();
scrollPane.setViewportView(table);
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
int fila = table.rowAtPoint(arg0.getPoint());
datoDirector.setId(Integer.parseInt(table.getValueAt(fila, 0).toString()));
datoDirector.setNombre(table.getValueAt(fila, 1).toString());
// Obtener la columna Fecha Nacimiento
Date date;
try {
date = (Date) new SimpleDateFormat("yyyy-MM-dd").parse((String)table.getValueAt(fila, 2));
datoDirector.setFechaNacimiento(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I want to get the date as type DATE
to save it in a local variable type DATE
as well (I'll place it in a JDateChooser with its function .set ()).
rs.getDate("fechaNacimiento").toString()
is correct or
can I eliminate the .toString()
?