我有一个Jtable,其中的一列显示了价格,该价格应该是可编辑的。但是,每当我尝试更新单元格值时,都会出现异常:
java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
我的产品的型号如下:
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
}
在我的自定义类中,扩展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;
}
}
我应该将价格更改为字符串吗?还有其他正常方法吗?如果我删除了getColumnClass,则价格更改有效,但是我无法显示产品Pic,因此这不是解决方案。
这条线有问题(我在“问题”中添加了您的代码所分析的内容)。您只能尝试将double
Object解析为,String
这是不可能的,java
因为String
和之间没有子对父母的关系Double
。
double price = Double.parseDouble((String)val); //trying to cast double as String.
这行代码将引发
ClassCastException
。因为val
是double
对象的类型而不是字符串。
您可以尝试使用此方法。
double price = (double)val; //try this
谢谢你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句