Scala:在TreeView

时间:2015-12-26 16:42:24

标签: java scala javafx treeview filepath

所以我试图展示我的整个" C:\"使用JavaFX在TreeView中驱动。 我已经以递归的方式完成了它也显示了子目录的内容等等但是我得到了很多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

1 个答案:

答案 0 :(得分:1)

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

这是我更新的代码:

    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()
    }

正如你所看到的,我添加了参数&#34; parent&#34;它始终显示文件的实际父级以及放置它们的位置,并在目录语句中将子目录设置为新父级... 尽管我仍然有很多

  

NullPointerException错误。

有谁知道为什么?

以下是现在的更新图片: WORKS but still with errors?