【发布时间】:2015-12-26 16:42:24
【问题描述】:
所以我正在尝试使用 JavaFX 在 TreeView 中显示我的整个“C:\”驱动器。 我已经以递归方式完成它以显示子目录的内容等等,但是我得到了很多 NullPointerExceptions 并且子目录中的文件也不会以适当的方式显示,比如能够扩展它,但就像全部在一个目录中...
val rootItem: TreeItem[String] = new TreeItem(System.getenv("SystemDrive"),new ImageView(pictureFolder))
//set a value for the picture of an folder Icon and use it for TreeItems
val pictureFolder: Image = new Image("/fhj/swengb/project/remoty/folder.png")
val pictureFile: Image = new Image("/fhj/swengb/project/remoty/file.png")
//first set the directory as string
val directory: File = new File("C:")
//use the array to store all files which are in the directory with list files
displayDirectoryContent(directory)
//iterate trough files and set them as subItems to the RootItem "C:"
def displayDirectoryContent(dir: File): Unit = {
try{
val files: Array[File] = dir.listFiles()
for(file <- files){
if(file.isFile && !file.isHidden){
val item = new TreeItem[String](file.getAbsolutePath,new ImageView(pictureFile))
rootItem.getChildren.add(item)
}
else if(file.isDirectory && !file.isHidden){
val item = new TreeItem[String](file.getAbsolutePath,new ImageView(pictureFolder))
rootItem.getChildren.add(item)
displayDirectoryContent(file)
}
}
}catch {
case e: IOException => e.printStackTrace()
case n: NullPointerException => n.printStackTrace()
}
那么有谁知道如何解决 NullPointerExceptions 的问题,以及为什么子目录中的文件没有以正确的方式显示?
【问题讨论】:
-
您始终使用以下行添加文件:rootItem.getChildren.add(item),因此它们始终处于同一级别;根级别。您可以向递归函数添加另一个参数,即当前级别。添加目录时,将这个新创建的级别向下传递。
-
@Carl 嗯,这听起来是对的,但你的意思是向下或向上一层?无法完全按照您的想法进行操作?
标签: java scala javafx treeview filepath