UPDATE: It doesn't have to be using static files. Is using a global variable string and listening to if that changed in length possible?
WHAT AM I TRYING TO DO: Basically, I am trying to represent a visual tree representation of an xml document that is rendered on the other Jpanel. When I select node on this rendered xml document, I want to add that xml node onto the visual tree. So essentially, the rendered componenet and the visual tree componenent share the same xml file/variable.
THE PROBLEM (I am open to alternate suggestions) :
I have a visual tree generated by the following method using org.apache.xerces.parsers.SAXParser.
It reads an xml file and returns the scrollPane component to be rendered on screen.
I need to be able to add or remove nodes and edit. So when I click a button, it will add a node to the visual tree. However, I think there needs to be some event listener when the xml file has been updated to quickly dr开发者_运维技巧aw the tree. This might be inefficient (?) because it requires redrawing the tree everytime xml file change event happens?
private static Component createTree() {
DefaultMutableTreeNode top = new DefaultMutableTreeNode("test"));
SAXTreeBuilder saxTree = new SAXTreeBuilder(top);
try {
SAXParser saxParser = new SAXParser();
saxParser.setContentHandler(saxTree);
saxParser.parse(new InputSource(new FileInputStream("test1.xml")));
}catch(Exception ex){
ex.printStackTrace();
top.add(new DefaultMutableTreeNode(ex.getMessage()));
}
JTree tree = new JTree(saxTree.getTree());
JScrollPane scrollPane = new JScrollPane(tree);
return scrollPane;
}
First store the modification time of an XML file in a temporary variable while drawing the tree for the first time then Use a thread or TimerTask to keep track of the modification time ,if there is any change in modification time compared to temporary variable that means XML file is modified.call your tree view generation code.
A change event for files doesn't exist. You only option is to write a polling thread calling java.io.File.lastModified() on your file. Depending on the situation that might be enough and the performance penalty not too high.
If you want you can also use this library from Apache commons
精彩评论