I have a Jtable with one of the columns presenting price which should be editable. But whenever I try to update the cell value I get the exception:
java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
the model for my product is as follows:
public class Product{
private double price;
private String name;
private Icon pic;
public Product(String name, double price){
this.name= name;
this.price = price;
}
public void setPrice(double price){
this.price = price;
}
//other getters and setters
}
In my custom class extending AbstractTableModel:
private ArrayList<Product> products;
//constructor and other methods
public void setValueAt(Object val, int row, int col) {
if (col == 2){
try{
double price = Double.parseDouble((String)val);
products.get(row).setPrice(price);
}
catch(Exception e){
}
fireTableCellUpdated(row, col);
}
}
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public Object getValueAt(int rowNo, int column) {
Product item = products.get(rowNo);
switch(column){
case 0: return item.getPic();
case 1: return item.getName();
case 2: return item.getPrice();
default: return null;
}
}
Should I change the price to string? Is there any other normal way to do this? If I remove getColumnClass override price change works, but then I cannot display product Pic so this is not a solution.
problem with this line (what i analysed by your Code added in Question). You just try to parse a double
Object into a String
which is not possible in java
because there is no child-parent relationship between String
and Double
.
double price = Double.parseDouble((String)val); //trying to cast double as String.
This line of code will raise
ClassCastException
. because ofval
is adouble
type of Object not a String.
you may try this should works fine.
double price = (double)val; //try this
Thank You.