2016-06-14 66 views
1

我有一个Jtable,其中一列显示应该可编辑的价格。但每当我尝试更新单元格的值我得到异常:Java swing如何在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,所以这不是一个解决方案。

+0

请分享你的'getValueAt'方法。 – rdonuk

+0

为什么原因有双重价格= Double.parseDouble((String)val); btw DefaultTTableCellEditor可以retuns对象,在这种形式的问题(基于你的问题中的描述和代码)是不应答的,或者答案太宽,很多时候在这里相似的问题... – mKorbel

+0

@rdonuk我更新了代码。 mKorbel不是用户输入的只是一个字符串值,我需要解析以加倍? – cAMPy

回答

1

这条线的问题(我在问题中加入了你的代码进行了分析)。您只是尝试将double对象解析为String,这在java中不可行,因为StringDouble之间没有子父母关系。

double price = Double.parseDouble((String)val); //trying to cast double as String. 

这行代码将提高ClassCastException。因为valdouble类型的Object not a String。

你可以试试这个应该可以。

double price = (double)val; //try this 

谢谢。

相关问题