Reloading a JTree during runtime
- by Patrick Kiernan
I create a JTree and model for it out in a class separate to the GUI class. The data for the JTree is extracted from a file.
Now in the GUI class the user can add files from the file system to an AWT list. After the user clicks on a file in the list I want the JTree to update. The variable name for the JTree is schemaTree.
I have the following code for the when an item in the list is selected:
private void schemaListItemStateChanged(java.awt.event.ItemEvent evt) {
int selection = schemaList.getSelectedIndex();
File selectedFile = schemas.get(selection);
long fileSize = selectedFile.length();
fileInfoLabel.setText("Size: " + fileSize + " bytes");
schemaParser = new XSDParser(selectedFile.getAbsolutePath());
TreeModel model = schemaParser.generateTreeModel();
schemaTree.setModel(model);
}
I've updated the code to correspond to the accepted answer. The JTree now updates correctly based on which file I select in the list.