当我尝试使用向量填充JTable
时,出现以下错误。
错误:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Vector
at javax.swing.table.DefaultTableModel.justifyRows(DefaultTableModel.java:268)
at javax.swing.table.DefaultTableModel.setDataVector(DefaultTableModel.java:224)
at javax.swing.table.DefaultTableModel.<init>(DefaultTableModel.java:159)
at Package_Sync.Package_sync$Model.<init>(Package_sync.java:50)
at Package_Sync.Package_sync.packageTable(Package_sync.java:43)
at Package_Sync.Package_sync.<init>(Package_sync.java:16)
at Package_Sync.Package_sync$2.run(Package_sync.java:116)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
这是我的代码:
private void packageTable() {
Vector tableHeadings = new Vector();
tableHeadings.add("PACKAGE NAMES");
tableHeadings.add("SHOW");
Table1.setModel(new Model(fileVector, tableHeadings));
}
class Model extends DefaultTableModel {
Vector heading = null;
Model(Vector data, Vector heading) {
super(data, heading);
this.heading = heading;
}
public Class getColumnClass(int cols) {
if (getValueAt(0, cols) != null && cols > 0) {
return getValueAt(0, cols).getClass();
} else {
return String.class;
}
}
}
我的代码有什么问题?
最佳答案
从异常中,必须将String对象添加到fileVector中,如下所示:
Vector fileVector = new Vector();
fileVector.add("a string object");
这与DefaultTableModel的实现相反,要使用它,您需要将Vector对象添加到fileVector中,如下所示:
Vector fileVector = new Vector();
fileVector.add(new Vector(Arrays.asList(new String[]{"row1 col1", "row1 col2"})));
fileVector.add(new Vector(Arrays.asList(new String[]{"row2 col1", "row2 col2"})));
干杯