在运行时重新加载 JTree
我在独立于 GUI 类的类中创建了一个 JTree 和模型。 JTree 的数据是从文件中提取的。
现在,在 GUI 类中,用户可以将文件从文件系统添加到 AWT 列表。 用户单击列表中的文件后,我希望更新 JTree。 JTree 的变量名称是 schemaTree。
当选择列表中的项目时,我有以下代码:
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);
}
我已更新代码以对应于接受的答案。 JTree 现在根据我在列表中选择的文件正确更新。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 < code>Component.add API 文档。
您对未显示的组件调用了
repaint
和validate
,这不会生效。 您需要在add
之后调用mainPanel
上的这些方法。 此外,revalidate
往往比validate
更好,因为它有效地合并。From the
Component.add
API docs.You have called
repaint
andvalidate
on a component that is not displayed, which will not be effective. You need to call those methods on themainPanel
after theadd
. Alsorevalidate
tends to be better thanvalidate
as it effectively coalesces.我不确定我是否理解你的问题,但我会尝试...
正确的做法应该是,恕我直言:
在伪代码中,它会看起来像这样:
然后 JTree 将被更新,没有任何调用重新绘制等。
希望它有帮助
I not sure that I'm understanding your question, but I'll try...
The right thing to do should be, IMHO:
In pseudocode, it would look like that:
then the JTree would be updated, without any call to repaint, etc.
Hope it helps