Я изменяю приложение, которое загружает данные динамически из файла XML, который содержит тест и отображает вопросы и ответы.Изменение заключается в том, что я хочу загрузить один (пока жестко запрограммированный) файл вместо использования JFileChooser.
Вот соответствующий код, работавший раньше (неопределенные переменные являются атрибутами класса, но я не буду публиковатьобъявление всего класса):
public ClassConstructor()
{
JMenuItem load = new JMenuItem("Load");
...
}
load.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
if(status == UNSAVED_CHANGES)
if(JOptionPane.showConfirmDialog(gThis , "There are unsaved changes. Continue?" , "Unsaved changes" , JOptionPane.OK_CANCEL_OPTION) == 2)
return;
int returnVal = filePick.showOpenDialog(new JPanel());
if(returnVal == JFileChooser.APPROVE_OPTION)
{
try
{
load(filePick.getSelectedFile().getCanonicalPath());
pathname = filePick.getSelectedFile().getCanonicalPath();
}
catch(IOException f)
{
System.out.println(f);
}
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
status = FILE_LOADED;
}
}
}
);
private static void load(String fileName)
{
System.out.println(fileName);
try
{
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(new DefaultHandler());
theBase = db.parse(fileName);
idno = Integer.parseInt(((Element)(theBase.getElementsByTagName("base").item(0))).getAttribute("idno"));
System.out.println(idno);
lastName = fileName;
status = FILE_LOADED;
}
catch(IOException e)
{
System.out.println(e);
}
catch(ParserConfigurationException p)
{
System.out.println(p);
}
catch(SAXException s)
{
System.out.println(s);
}
}
public static void setupQuestion(String qid)
{
linkids = new Vector();
links = new Vector();
qdata = new Vector();
Element e = theBase.getElementById(qid);
question.setText(e.getAttribute("value"));
int items = 0;
NodeList nl = e.getChildNodes();
for(int i=0; i < nl.getLength(); i++)
{
if(nl.item(i).getNodeType() == Node.ELEMENT_NODE)
{
items++;
qdata.add(((Element)nl.item(i)).getAttribute("content") );
linkids.add(((Element)nl.item(i)).getAttribute("link"));
links.add((Element)nl.item(i));
}
}
replies.setListData(qdata);
thisq = qid;
}
А теперь код, который не работает:
public ClassConstructor()
{
//JMenuItem load = new JMenuItem("Load");
load("C:\\file.xml");
pathname = "C:\\file.xml";
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
}
// i've dropped load.addActionListener() but rest of the code has no changes
Кроме того, исключение:
Exception in thread "main" java.lang.NullPointerException
и этопроисходит в question.setText(e.getAttribute("value"));
при вызове setupQuestion("q1");
.
Редактировать: Интересно, что System.out.println(fileName);
печатается до того, как сгенерировано исключение, и System.out.println(idno);
печатается после него. На самом деле при перезапуске IDE оба эха появляются послеисключение брошено.
Я застрял на этом в течение достаточно долгого времени.Любая помощь очень ценится.