gpt4 book ai didi

java - Scala:在 TreeView 中显示 systemDrive

转载 作者:行者123 更新时间:2023-11-30 10:52:07 25 4
gpt4 key购买 nike

因此,我正在尝试使用 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 的问题以及为什么子目录中的文件没有以正确的方式显示?

这是一张图片: How it looks like now

最佳答案

所以我尝试了一些不同的东西,现在我的代码可以工作了,所以它列出了该目录中子目录的所有文件:

这是我更新后的代码:

    val rootItem: TreeItem[String] = new TreeItem(System.getenv("SystemDrive"),new ImageView(pictureFolder))

val pictureFolder: Image = new Image("/fhj/swengb/project/remoty/folder.png")
val pictureFile: Image = new Image("/fhj/swengb/project/remoty/file.png")


val directory: File = new File("C:")


displayDirectoryContent(directory)


def displayDirectoryContent(dir: File,parent: TreeItem[String] = rootItem): Unit = {
try{
val files: Array[File] = dir.listFiles()
for(file <- files){
if(file.isFile && !file.isHidden){
val file = new TreeItem[String](file.getAbsolutePath,new ImageView(pictureFile))
parent.getChildren.add(file)
}
else if(file.isDirectory && !file.isHidden){
val subdir = new TreeItem[String](file.getAbsolutePath,new ImageView(pictureFolder))
parent.getChildren.add(subdir)
displayDirectoryContent(file,subdir)

}
}

}catch {
case e: IOException => e.printStackTrace()
case n: NullPointerException => n.printStackTrace()
}

如您所见,我添加了参数“parent”,它始终显示文件的实际父级以及放置它们的位置,并且在目录语句中,子目录被设置为新的父级...虽然我还是得到了很多

NullPointerException errors.

有人知道为什么吗?

这是更新后的图片现在的样子: WORKS but still with errors?

关于java - Scala:在 TreeView 中显示 systemDrive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34473252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com