views:

757

answers:

2

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.

+2  A: 

From the Component.add API docs.

Note: If a component has been added to a container that has been displayed, validate must be called on that container to display the new component. If multiple components are being added, you can improve efficiency by calling validate only once, after all the components have been added.

You have called repaint and validate on a component that is not displayed, which will not be effective. You need to call those methods on the mainPanel after the add. Also revalidate tends to be better than validate as it effectively coalesces.

Tom Hawtin - tackline
I've tried revalidate on the mainPanel however the JTree still doesn't update. I'll modify the code in the original question to what I have now
Patrick Kiernan
It looks like you've now not added the new tree to the panel.
Tom Hawtin - tackline
Works now .. I now don't remove the JTree at all, I just wasn't updating the model in the correct place.Thanks for your reply
Patrick Kiernan
+1  A: 

I not sure that I'm understanding your question, but I'll try...

The right thing to do should be, IMHO:

  • get the file
  • create a new TreeModel from your file
  • give the model to the JTree

In pseudocode, it would look like that:

File newContent = getSelectedByUser(...);
TreeModel newModel = new MyFileBasedTreeModel(newContent);
//this next part must be done in the EventDispatcherThread
myTree.setModel(newModel);

then the JTree would be updated, without any call to repaint, etc.

Hope it helps

Laurent K
Very good, I've now modified the method generateTree() to return the model instead of the tree and renamed the method generateTreeModel(). The tree now updates correctly based on which file I click in the list. Thanks!
Patrick Kiernan