扩展时DefaultTabelModel类强制转换异常

时间:2013-11-16 07:53:17

标签: java swing vector classcastexception defaulttablemodel

List<MyProduct> myProducts = getMyProducts();//create an arraylist;
Vector dataVector = new Vector(myProducts);
Vector columnVector = new Vector(myColNames); //Just a list of string headers
setDataVector(dataVector, columnVector);

setDataVector在DefaultTableModel中调用这段代码并抛出突出显示的classcast异常,看起来像个bug?因为它试图将元素转换为向量,这没有意义。

private void justifyRows(int from, int to) {
        // Sometimes the DefaultTableModel is subclassed
        // instead of the AbstractTableModel by mistake.
        // Set the number of rows for the case when getRowCount
        // is overridden.
        dataVector.setSize(getRowCount());

        for (int i = from; i < to; i++) {
            if (dataVector.elementAt(i) == null) {
                dataVector.setElementAt(new Vector(), i);
            }
            //java.lang.ClassCastException:
            ((Vector)dataVector.elementAt(i)).setSize(getColumnCount());
        }
    }

2 个答案:

答案 0 :(得分:2)

List<MyProduct> myProducts = getMyProducts(); //create an arraylist;
Vector dataVector = new Vector(myProducts);

这使得dataVector MyProduct的向量不是向量的向量。我认为这是你的问题。

答案 1 :(得分:1)

   java.lang.ClassCastException:
  ((Vector)dataVector.elementAt(i)).setSize(getColumnCount());

setDataVector(Vector dataVector, Vector columnIdentifiers):实际上需要Vector包含一个或多个Vector:代表表格数据rows。如果与其他函数setDataVector(Object[][] dataVector, Object[] columnIdentifiers)进行比较,您会更好地理解。

在返回您的ArrayList myProducts后,添加此内容,创建一个Vector例如prodVect,其中包含该列表的元素,并将该向量添加到另一个Vector

List<MyProduct> myProducts = getMyProducts();//create an arraylist;
Vector prodVector = new Vector(myProducts);
Vector dataVector = new Vector();
dataVector.add(prodVector);
setDataVector(dataVector, columnVector);

但是,我认为您可以使用setDataVector而不是依赖model.addRow(prodVector)函数,其中prodVectorVector,如上所述。另一个是model.addRow(Object[])函数,您可能知道并且优于使用带有Vector参数的函数。