我已经解析了一个XML文件,其中包含一些我希望在JList
中显示的元素。
解析工作正常,但在Jlist
中显示它根本不起作用。
我尝试过以下操作:
DefaultModelList
。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
方法将我的模型调用到JList
。 initialize()
的重要部分如下所示:
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();
}
}
答案 0 :(得分:1)
您正在创建单例实例,但您忘记初始化它。变化:
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;
}