B4J Question Example of a TreeView in Java

Sergey_New

Well-Known Member
Licensed User
Longtime User
I give an example of a TreeView in Java.
B4X:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;

public class TreeViewMain extends Application {
    @Override
    public void start(Stage stage) throws IOException {

        File filePath = new File("D:\\IDEA Projects"); // you can change the path here to your desired path
        
        // Create the root and items
        TreeItem<String> root = createItems(filePath);

        // create the treeview
        TreeView<String> treeView = new TreeView<>(root);

        // Create the Scene and show the stage
        VBox layout = new VBox(treeView);
        Scene scene = new Scene(layout, 400, 400);
        stage.setScene(scene);
        stage.setTitle("JavaFX TreeView");
        stage.show();

        // This code will print out the selected items on the TreeView
        treeView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue ) ->{
            String selectedItem = newValue.getValue();
            System.out.println(selectedItem);
        });
    }

    // create the treeitems dynamically based on the given path
    private TreeItem<String> createItems(File file){
        TreeItem<String> treeItems = new TreeItem<>(file.getName());
        if(file.isDirectory()){
            File[] files = file.listFiles();
            if(files != null){
                for(File childItem : files){
                    treeItems.getChildren().addAll(createItems(childItem));
                }
            }
        }

        return treeItems;
    }

    public static void main(String[] args) {
        launch();
    }
}
Please create this example using B4J.
 

MicroDrie

Well-Known Member
Licensed User
This site possesses a fantastic search engine in finding a solution. What is your problem with the second search result of the treeview search?
 
Upvote 0

MicroDrie

Well-Known Member
Licensed User
It is very difficult for anyone to find a solution to a problem that you are the only one experiencing. And if you do not clearly show us your problem with a short description and preferably a small example program that contains that problem, there will unfortunately be no solution for you.
 
Upvote 0

Sergey_New

Well-Known Member
Licensed User
Longtime User
The problem is obvious from the example provided. It is necessary to build a tree-like representation of the computer’s file system, starting with an arbitrary folder, so that both the folders and the files included in them are visible. You can do it?
 
Upvote 0

zed

Active Member
Licensed User
We cannot code for you. You have to do it yourself. Your way of asking that we do things for you does not correspond to the spirit of this forum.
Please create this example using B4J.
A member tells you that he cannot find a solution with the elements given and your response is very prompt.
This behavior does not seem correct.
The problem is obvious from the example provided
We can help everyone.
But we expect respect and a start of code which shows that you have at least tried to do it yourself.
 
Upvote 0

Sergey_New

Well-Known Member
Licensed User
Longtime User
Your phrase does not correspond to reality, that the member tells you that he cannot find a solution with the elements given.
Perhaps these are translation errors, I don't know English.
 
Upvote 0

PaulMeuris

Active Member
Licensed User
Show me your B4J code and i will compare it to mine!
1705751301216.png

You should use a recursive subroutine as it is demonstrated in the Java code snippet.
 
Upvote 0

zed

Active Member
Licensed User
Here is a complete system with hard drive and USB key and ContextMenu
Adapt it to your code. If you still have problems please ask again

B4J:
    'TreeView variable
    Private TreeView1 As TreeView
    Private rootdir As String
    Private CurrentDrive As String
    Private CurrentPath As String
    Private CurrentFile As String
    Private lblTreeviewPath As Label
    Private lineTRV As Pane
    Private CtMenu As ContextMenu

B4J:
#Region TreeView
Private Sub DriveList
    'List all PC drives and add them to the CLV
    Dim mDrive As String
    Dim fsv As JavaObject
    fsv.InitializeStatic("javax.swing.filechooser.FileSystemView")
   
    For Each drive As Object In ListRoots
        mDrive = fsv.RunMethodJO("getFileSystemView",Null).RunMethod("getSystemDisplayName",Array(drive)) 'Get Drive Name
        clvDrive.Add(ItemDrive(clvDrive.AsView.Width,mDrive),drive) 'add Item
    Next
End Sub
   
Sub ListRoots As List
    Dim jo As JavaObject
    Dim o() As Object = jo.InitializeStatic("java.io.File").RunMethod("listRoots", Null)
    Return o
End Sub

Private Sub ItemDrive(Width As Int, s As String) As Pane
    Dim p As B4XView = xui.CreatePanel("")
    Dim height As Int = 20dip
    p.SetLayoutAnimated(0, 0, 0, Width, height)
    p.Color = xui.Color_Transparent
    p.LoadLayout("itemDrive")
    lblDrive.Text = s
    Return p
End Sub

Private Sub clvDrive_ItemClick (Index As Int, Value As Object)
    pn_5.As(B4XView).BringToFront
    CurrentDrive = Value
    LoadTreeview(Value)'drive selected
End Sub

Private Sub LoadTreeview(mDrive As String)
   
    TreeView1.Root.Children.Clear
    rootdir = mDrive
   
    lblTreeviewPath.text = rootdir
    lblTreeviewPath.TooltipText = rootdir

    Private FolderImage As Image
    FolderImage = fx.LoadImage(File.DirAssets, "folderico.png")
   
    AddFolder(TreeView1.Root, mDrive, FolderImage)
   
End Sub


Sub AddFolder(Parent As TreeTableItem, Folder As String, img As Image)
    TreeView1.Root.Children.Clear
    CurrentPath = Folder

    'first item to go back
    Dim ti As TreeItem
    ti.Initialize(Folder,"...")
    ti.Image = xui.LoadBitmap(File.DirAssets,"folderback.png")
    Parent.Children.Add(ti)
   
    'All Item
    For Each f As String In File.ListFiles(Folder)
       
        Dim ti As TreeItem
        Dim Name As String = f
        ti.Initialize("ti", Name)
       
        If File.IsDirectory(Folder, f) Then
            'Folder
            Parent.Children.Add(ti)
            ti.Expanded = False
            ti.Image = img
        Else
            'File - Only shows files with the extension
            Dim extension As String = ti.text
            extension = extension.SubString(extension.LastIndexOf(".") )
            If extension = ".wav" Or extension = ".mp3" Or extension = ".ogg" Or extension = ".flac" Then
                Parent.Children.Add(ti)
                ti.Image = xui.LoadBitmapResize(File.DirAssets,"soundICO.png",16,16,True)
            End If
        End If
       
    Next

End Sub

Private Sub TreeView1_SelectedItemChanged (SelectedItem As TreeItem)

    If SelectedItem.IsInitialized = False Then Return
    Dim ti As TreeItem = SelectedItem

    If SelectedItem.Text = "..." Then 'First item clicked - go back
    '    Log("here"&CurrentPath)
        If CurrentPath = CurrentDrive Then Return
        CurrentPath = CurrentPath.SubString2(0, CurrentPath.LastIndexOf("\"))
        If CurrentPath.Contains("\") = False Then CurrentPath = CurrentPath & "\"
        LoadTreeview(CurrentPath)

    Else If File.IsDirectory(rootdir, ti.Text) = True Then 'If it is a folder on list of subfolders
        CurrentPath = CurrentPath&"\"&SelectedItem.text
        CurrentPath = CurrentPath.Replace("\\","\")
'        Log(CurrentPath)
        LoadTreeview(CurrentPath)'list of subfolders
    Else
        'Let's test the file extension to figure out if its an image
        Dim extension As String = ti.text
        extension = extension.SubString(extension.LastIndexOf(".") )
        Select extension
            Case ".wav", ".mp3",".ogg",".flac"
                CurrentFile = ti.text 'FileName
        End Select
    End If
   
End Sub

Private Sub TreeView1_MouseClicked (EventData As MouseEvent)
    pn_5.As(B4XView).BringToFront
   
    If EventData.PrimaryButtonPressed =True Then
        'Leftmouse clicked
        If File.IsDirectory(CurrentPath, CurrentFile) = False Then' Return
            'Save the current Path
            File.WriteString(File.DirApp, "path.txt", CurrentPath)
            'Convert the file to load it into AudioClip
            'Preview selected sound
            convert(CurrentPath,CurrentFile,"treeview")
        End If
    End If
   
    If EventData.SecondaryButtonPressed =True Then
        'Rightmouse clicked
        If File.IsDirectory(CurrentPath, CurrentFile) Then Return
        'Load context menu if it's a sound file only
        Dim CMJO As JavaObject = CtMenu
        Dim XOffset As Double = -TreeView1.Width + EventData.X
        Dim YOffset As Double = EventData.Y
        CMJO.RunMethod("show",Array(TreeView1,"RIGHT",XOffset,YOffset))
   
    End If
   
End Sub

'Right Click mouse - ContextMenu Choice
Sub MI_Action
    Dim MItem As MenuItem = Sender
    If MItem.Text.Contains("Beatmaker") Then
        Log("beatMaker : "&CurrentPath&"---"&CurrentFile)
        convert(CurrentPath,CurrentFile,"Beatmaker")
    End If
    If MItem.Text.Contains("track") Then
        Log("pianoroll : "&CurrentPath&"---"&CurrentFile)
        convert(CurrentPath,CurrentFile,"Track")
    End If
End Sub

Private Sub lblTreeviewPath_MousePressed (EventData As MouseEvent)
    pn_5.As(B4XView).BringToFront
End Sub
#End Region
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
Here is a simple example in B4XPages (based on the link posted by @MicroDrie above)

B4X:
Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Private TreeView1 As TreeView
End Sub

Public Sub Initialize
'    B4XPages.GetManager.LogEvents = True
End Sub

Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
    PopulateTreeview
End Sub

Private Sub PopulateTreeview
    Dim Directory As String = "C:\B4X"
    'For Each File1 As String In File.ListFiles(Directory)
    '    Log(File1)
    '    If File.IsDirectory(Directory, File1) Then          
    '        For Each File2 As String In File.ListFiles(File.Combine(Directory, File1))
    '            Log("    " & File2)
    '        Next
    '    End If
    'Next
    For Each File1 As String In File.ListFiles(Directory)
        Dim ti As TreeItem
        ti.Initialize("ti", File1)
        If File.IsDirectory(Directory, File1) Then
            For Each File2 As String In File.ListFiles(File.Combine(Directory, File1))
                Dim cti As TreeItem
                cti.Initialize("ti", File2)
                ti.Children.Add(cti)
            Next
        End If
        TreeView1.Root.Children.Add(ti)
    Next
End Sub

1705763405115.png
 
Upvote 0

zed

Active Member
Licensed User
I would like to see as many as there are in reality.
you can't have all the levels in one go. It would take a long time and eventually break. You must use recursion.
Nothing prevents you from saving the levels in a database and recreating them as needed
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
Clear, but how do you know that a node has children? The arrow is not displayed...
Same with how do I know Directory has children. I do not need to know prior because I use For loop. If no child, nothing happens. I think you can also load 2 levels down with every level clicked. Programming is a job of thinking.
 
  • Like
Reactions: zed
Upvote 0
Top