O. Martinez O. Martinez - 4 months ago 17
Java Question

Error with types in JTable

I've got a JTable with 2 columns. The first one just contents the names of the days of the week, and the second one contents a

double
value.

There're three buttons:


  • Auto-generating
    double
    values for testing, with this method:

    private void autoGenerate(java.awt.event.ActionEvent evt) {
    for (int a=0; a<Config.n; a++){
    tabla.setValueAt(a - a*0.5, a, 1);}


    }

  • To plot.

  • To save the values of the table in the BD



When I try to save the data into the BD after having generated the values with the
autoGenerate
button everything works.
However when I try to save the data into the BD after having typed the values manually an error occurs:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
at project.Graph.jButton5ActionPerformed(Graph.java:286)


The button that saves the data does this:

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt,Patient p) {
try {
for (int k = 0; k < Config.n; k++) {
DBManager.save(p, k+1,(double)this.table.getValueAt(k, 1));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}

Answer

However when I try to save the data into the BD after having typed the values manually an error occurs:

Without any other modifications to the column classes or CellEditor, editing the value via the JTable UI will result in a String object being stored in the model. Thus the ClassCastException when retrieving the value and attempting to cast to a double. Consider explicitly defining the column class via the TableModel - this not only results in a Double object being stored in the model, but also affects the CellEditor as well (avoiding any errors when inputting non-numeric data).

DefaultTableModel model = new DefaultTableModel(){
    @Override
    public Class<?> getColumnClass(int col){
        if ( col ==  1 ){
            return Double.class;
        }
        return String.class;
    }
    @Override
    public int getColumnCount(){
        return 2;
    }
};
JTable table = new JTable(model);
Comments