我有 XML 解析的数据,我正在尝试将其添加到 DefaultTableModel 中。 根据文档,DefaultTableModel 将 Vectors 或 Object[] 作为参数。
但是当我使用 Vector 时,我得到了这个异常:
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Vector
这是我用来解析并添加到 vector 中的类。
public class PropXMLParsing {
static PropXMLParsing instance = null;
private Vector<String> header = new Vector<String>();
private Vector<String> data = new Vector<String>();
public static PropXMLParsing getInstance() {
if (instance == null) {
instance = new PropXMLParsing();
try {
instance.ParserForObjectTypes();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
return instance;
}
public void ParserForObjectTypes() throws SAXException, IOException,
ParserConfigurationException {
try {
FileInputStream file = new FileInputStream(new File(
"xmlFiles/CoreDatamodel.xml"));
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//prop/*";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(
xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild()
.getNodeValue());
data.addElement(nodeList.item(i).getFirstChild().getNodeValue());
header.addElement(nodeList.item(i).getFirstChild()
.getNodeValue());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
public Vector<String> getHeader() {
return header;
}
public Vector<String> getData() {
return data;
}
}
最后一行代码是抛出异常的地方。这是来 self 的 GUI 类:
model = new DefaultTableModel(PropXMLParsing.getInstance().getHeader(),
PropXMLParsing.getInstance().getData());
table = new JTable(model);
请帮帮我
最佳答案
根据the javadoc for DefaultTableModel ,数据必须是 Vector<Vector<String>>
。此外,您还可以在 DefaultTableModel 构造函数参数中向后获取数据和 header 。
关于java.lang.ClassCastException : java. lang.String 无法转换为 java.util.Vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21254501/