简体   繁体   English

在运行时重新加载JTree

[英]Reloading a JTree during runtime

I create a JTree and model for it out in a class separate to the GUI class. 我创建了一个JTree并在与GUI类不同的类中为其建模。 The data for the JTree is extracted from a file. JTree的数据是从文件中提取的。

Now in the GUI class the user can add files from the file system to an AWT list. 现在,在GUI类中,用户可以将文件系统中的文件添加到AWT列表中。 After the user clicks on a file in the list I want the JTree to update. 用户单击列表中的文件后,我希望JTree更新。 The variable name for the JTree is schemaTree. JTree的变量名称为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. 现在,JTree将根据我在列表中选择的文件正确更新。

From the Component.add API docs. 来自Component.add API文档。

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. 注意:如果已将组件添加到已显示的容器中,则必须在该容器上调用validate以显示新组件。 If multiple components are being added, you can improve efficiency by calling validate only once, after all the components have been added. 如果要添加多个组件,则可以在添加完所有组件之后仅调用一次validate来提高效率。

You have called repaint and validate on a component that is not displayed, which will not be effective. 您已调用repaint并在未显示的组件上进行validate ,这将无效。 You need to call those methods on the mainPanel after the add . 您需要在add之后在mainPanel上调用这些方法。 Also revalidate tends to be better than validate as it effectively coalesces. 由于有效合并, revalidate往往比validate要好。

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 从文件创建一个新的TreeModel
  • give the model to the JTree 将模型交给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. 然后将更新JTree,而无需调用任何重绘等。

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM