gpt4 book ai didi

java - 将 XML 解析值添加到 JList 中不起作用

转载 作者:行者123 更新时间:2023-11-30 11:23:25 26 4
gpt4 key购买 nike

我已经解析了一个 XML 文件,其中包含一些我想在 JList 中显示的元素。解析工作正常,但在 Jlist 中显示它根本不起作用。

我已尝试执行以下操作:

  1. 解析 XML。
  2. 将节点添加到 DefaultModelList
  3. 将模型添加到Jlist

我的代码:

public class ReadXMLFile {

private DefaultListModel model = new DefaultListModel();

private static ReadXMLFile instance = null;

public static ReadXMLFile getInstance() {

if (instance == null) {

instance = new ReadXMLFile();

}

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 = "//OBJECT_TYPE";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(
xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {

model.addElement(nodeList.item(i).getFirstChild()
.getNodeValue());
System.out.println(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 DefaultListModel getModel() {
return model;
}

}

然后在我的 GUI 构造函数中调用我的 initialize 方法,它将我的模型放入 JListinitialize() 的重要部分如下所示:

private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 823, 515);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JList obTypeJList = new JList(ReadXMLFile.getInstance().getModel());
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);

JMenu contentMenuBar = new JMenu("File");
menuBar.add(contentMenuBar);

JMenuItem OpenFileItemMenu = new JMenuItem("Open File");
contentMenuBar.add(OpenFileItemMenu);

}


public XmlEditorMain() {
initialize();
ReadXMLFile file = new ReadXMLFile();
try {
file.ParserForObjectTypes();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}

最佳答案

您正在创建单例实例,但您忘记了初始化它。变化:

public static ReadXMLFile getInstance() {
if (instance == null) {
instance = new ReadXMLFile();
}
return instance;
}

public static ReadXMLFile getInstance() {
if (instance == null) {
instance = new ReadXMLFile();
instance.ParserForObjectTypes();
}
return instance;
}

关于java - 将 XML 解析值添加到 JList 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21231201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com