2015-12-26 4 views
2

Итак, я пытаюсь показать весь свой диск «C: \» в TreeView с помощью JavaFX. Я сделал это рекурсивным образом, чтобы показать содержимое подкаталогов и т. Д., Но я получаю много NullPointerExceptions, и файлы, которые находятся в подкаталоге, также не будут отображаться надлежащим образом, чтобы иметь возможность расширять его, но просто как его все в одном каталоге ...Scala: show systemDrive in TreeView

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

+0

Вы всегда добавлять файлы, используя следующую строку: rootItem.getChildren.add (пункт), поэтому они всегда на том же уровне; уровень корня. Вы можете добавить еще один параметр в свою рекурсивную функцию, которая является текущим уровнем. Когда вы добавляете каталог, пропустите этот вновь созданный уровень вниз. – Carl

+0

@ Карл хмм, это звучит правильно, но как вы имеете в виду один уровень вниз или вверх? Не можете ли вы следовать за тем, о чем вы думаете? – Bajro

ответ

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

Как вы можете видеть, что я добавил параметр «родитель», который всегда показывает фактический родитель файлов и куда поместить их, и при утверждении каталога подкаталог, задан s новый родитель ... Увы, я все еще получаю много

NullPointerException ошибки.

У кого-нибудь есть идея, почему?

Вот обновленный образ, как он выглядит сейчас: WORKS but still with errors?