Java - File Management System Using Netbeans

How to Create a File Manager Project In Java Netbeans

How to Create a File Manager Project In Java Netbeans


In this Java Tutorial we will see how How To Create a File Manager System Project in java swing using netbeans.
This java project allows users to navigate through their file system, copy, paste, and delete files and folders.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.
- Flatleaf library.

What We Will Do In This Project:

Create a method to update the displayed files and folders when the user navigates to a new directory.
- Create a method to delete entire directories and their contents.
- Create a method to copy files and folders from a source directory to a destination directory.
- Create a method to generate unique names for copied files to avoid overwriting existing files.
- Sets up buttons and event listeners to enable or disable various operations (copy, paste, delete) based on user selections.
- Use a JFileChooser to allow users to select a folder for initial navigation.





Project Source Code:


/**
 *
 * @author 1BestCsharp
 */

// downoload flatlaf library to make the app look better
// https://search.maven.org/artifact/com.formdev/flatlaf/3.1.1/jar?eh=


        

        // When you click on something in the table
        fileTable.addMouseListener(new MouseAdapter() {
            
            @Override
            public void mouseClicked(MouseEvent e)
            {
                // If you quickly click twice
                if(e.getClickCount() == 2)
                {
                    // Find the row you clicked on
                    int selectedRow = fileTable.getSelectedRow();
                    // If you clicked on a row
                    if(selectedRow >= 0)
                    {
                        // get the file name
                        String selectedFileName = (String) tableModel.getValueAt(selectedRow, 0);
                        // Make a new path to that file / directory
                        File selectedFile = new File(currentDirectory, selectedFileName);
                        // If it's a folder
                        if(selectedFile.isDirectory())
                        {
                            // Change to that folder
                            currentDirectory = selectedFile;
                            // Show the files / folders inside the folder
                            refreshList(currentDirectory);
                        }
                    }
                    
                }
            }
        });
        
        
        // When you press the button to go to the parent directory
        parentButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                
                // Find the Parent folder of the currentDirectory.
                File parentDirectory = currentDirectory.getParentFile();
                // If we found a folder.
                if(parentDirectory != null && parentDirectory.isDirectory())
                {
                    // Display the Parent Directory content
                    currentDirectory = parentDirectory;
                    refreshList(parentDirectory);
                }
                
            }
        });
        
        // When the "Copy" button is clicked
        copyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
             
                // Get the rows that are selected in the table
                int[] selectedRows = fileTable.getSelectedRows();
                // Prepare a place to store the files/folders we want to copy
                cliboardFiles = new ArrayList<>();
                
                // Go through each selected row
                for(int row : selectedRows)
                {
                    // Get the name of the file from the table
                    String fileName = (String) tableModel.getValueAt(row, 0);
                    // Create a "path" to the file we want to copy
                    File fileToCopy = new File(currentDirectory, fileName);
                    // Put the file in our clipboard (like when you copy text)
                    cliboardFiles.add(fileToCopy);
                }
                
                // Enable the "Paste" button so we can use it now
                pasteButton.setEnabled(true);
                
            }
        });
        
        // When "Paste" button is clicked
        pasteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               // If something is in the clipboard
                if(cliboardFiles != null)
                {
                    // Go through each thing in the clipboard
                    for(File file : cliboardFiles)
                    {
                        // If it's a folder
                        if(file.isDirectory())
                        {
                            // Get the folder's name
                            String folderName = file.getName();
                            
                            // Generate a unique name for the copied folder
                            File destFolder = generateUniqueFileName(currentDirectory, folderName);
                            
                            // Try to copy the folder to the new place
                            try
                            {
                                copyDirectory(file.toPath().toString(), destFolder.toPath().toString());
                            }
                            catch(IOException ex)
                            {
                                ex.printStackTrace();
                            }
                        }
                        
                        else if(file.isFile())
                        {
                            String fileName = file.getName();
                            File destFolder = generateUniqueFileName(currentDirectory, fileName);
                            
                            try
                            {
                                Files.copy(file.toPath(), destFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);        
                            }
                            catch(IOException ex)
                            {
                                ex.printStackTrace();
                            }
                        }
                        
                    }
                    
                    refreshList(currentDirectory);
                    
                }
                
                pasteButton.setEnabled(false);
                
            }
        });
        
        // When the "Delete" button is clicked
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                
                // Get the row of the selected file or folder in the table
                int selectedRow = fileTable.getSelectedRow();
                // If a file or folder is selected
                if(selectedRow >= 0)
                {
                    // Get the name of the selected file or folder
                    String selectedFileName = (String) tableModel.getValueAt(selectedRow, 0);
                    // Create a path to the selected file or folder
                    File fileToDelete = new File(currentDirectory, selectedFileName);
                    // If the selected file or folder actually exists
                    if(fileToDelete.exists())
                    {
                        try
                        {
                            // If it's a folder
                            if(fileToDelete.isDirectory())
                            {
                                // Call a special function to delete the whole 
                                deleteDirectory(fileToDelete);
                            }
                            else
                            {
                                // If it's just a file, delete it using a different method
                                Files.delete(fileToDelete.toPath());
                            }
                        }
                        catch(IOException ex)
                        {
                            ex.printStackTrace();
                        }
                    
                        // Refresh the list of files and folders in the current directory
                        refreshList(currentDirectory);
                    }
                }
                
            }
        });
    
    
        // Implement file navigation logic using JFileChooser
        // Step 1: Create a JFileChooser
        JFileChooser fileChooser = new JFileChooser();
        // Step 2: Set the tool to only choose folders, not other things
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        // Step 3: Start the tool in a familiar place called "home"
        fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        // Step 4: When someone does something with the tool (like clicking or choosing),
        // we want to know and do something too
        fileChooser.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
             
                // Step 5: Find out which folder was chosen
                File selectedFile = fileChooser.getSelectedFile();
                // Step 6: If a folder was really chosen (not nothing), let's do some things
                if(selectedFile != null)
                {
                    // Step 7: Remember the chosen folder as the current place
                    currentDirectory = selectedFile;
                    // Step 8: Show all the files and folders inside the chosen folder
                    refreshList(currentDirectory);
                    // Step 9: Make buttons active so we can copy and delete
                    copyButton.setEnabled(true);
                    deleteButton.setEnabled(true);
                }
                
            }
        });
        
        // Step 10: Open the file chooser so we can start choosing a folder
        fileChooser.showOpenDialog(this);
    
    

    
    // This method helps to show the list of files and folders in a special place.
    private void refreshList(File directory)
    {
        // First, we check if the location we are looking at is a folder.
        if(directory.isDirectory())
        {
            // We start by making the list empty, like cleaning up a table.
            tableModel.setRowCount(0);
            
            // Now we get a list of all the files and folders inside the location.
            File[] files = directory.listFiles();
            
            // If we found some files, let's go through each one.
            if(files != null)
            {
                for(File file : files)
                {
                    // We find out the name of each file or folder.
                    String name = file.getName();
                    
                    // We check if it's a folder or a file.
                    // If it's a folder, we call it a "Directory". If it's a file, we call it a "File".
                    String type = file.isDirectory() ? "Folder" : "File";
                    
                    // If it's a folder, we don't know its size, so we write a "-" instead.
                    // If it's a file, we tell its size in numbers.
                    String size = file.isDirectory() ? "-" : String.valueOf(file.length());
                    
                    // We put all this information into the table model.
                    tableModel.addRow(new Object[]{name, type, size});
                }
            }
        }
    }
    
    
    // This method helps delete a whole folder and everything inside it.
    // It needs a 'directory' to start deleting from.
    private void deleteDirectory(File directory) throws IOException
    {
        // First, we check if there are any files inside this folder.
        // If there are, we need to go through each one of them.
        File[] files = directory.listFiles();
        // If there are files in the folder...
        if(files != null)
        {
            // For each file in the folder...
            for(File file : files)
            {
                // If a file is actually a folder, we need to delete it too.
                if(file.isDirectory())
                {
                    // We use the same method to delete this folder and its contents.
                    deleteDirectory(file);
                }
                // If it's not a folder, it's a regular file.
                else
                {
                    // We simply delete the regular file.
                   Files.delete(file.toPath());
                }
            }
            
            // After we've deleted all the files inside the folder,
            // we can now delete the empty folder itself.
            Files.delete(directory.toPath());
        }
    }
    
    
 /**
 * Copies all the files and folders from the source directory to the destination directory.
 *
 * @param sourceDirectoryLocation The place where the things to copy are.
 * @param destinationDirectoryLocation The place where the things will be copied to.
 * @throws IOException If something goes wrong while copying.
 */
    public void copyDirectory(String sourceDirectoryLocation, String distinationDirectoryLocation) throws IOException
    {
        // Start looking at each file or folder inside the source directory.
        Files.walk(Paths.get(sourceDirectoryLocation))
                   .forEach(source->{
                       // Calculate where the file or folder should go in the destination directory.
                       Path destination = Paths.get(distinationDirectoryLocation, 
                                                   source.toString().substring(
                                                    sourceDirectoryLocation.length()
                                                   ));
                   
                       try
                       {
                           // Copy the file or folder to its new place in the destination directory.
                           Files.copy(source, destination);
                       }
                       catch(IOException ex)
                       {
                           ex.printStackTrace();
                       }
                       
                   });
        
    }
    
    
    // This method helps make sure our copied files have unique names
    private File generateUniqueFileName(File directory, String fileName)
    {
        // Get the main part of the file name and its extension
        String baseName = fileName;  // Let's call the main part of the name "baseName"
        String extension = "";       // Let's call the part after the dot "extension"
        
        // If there's a dot in the name (like "picture.jpg"), split it into base name and extension
        int extensionIndex = fileName.lastIndexOf('.');  // Find where the dot is
        if(extensionIndex != -1)
        {
            baseName = fileName.substring(0, extensionIndex);  // The part before the dot
            extension = fileName.substring(extensionIndex);           // The part after the dot
        }
        
        // We'll start counting from 1 to make sure our new name is unique
        int count = 1;
        // Combine the base name, count, and extension to make a new name
        File destFile = new File(directory, fileName);
        // As long as a file with this name already exists, let's make a new one
        while(destFile.exists())
        {
            destFile = new File(directory, baseName + "(" + count + ")" + extension);
            count++;  // Increase the count for the next try
        }
        
        // Finally, return the unique name we found
        return destFile;
        
    }
    




The Final Result:

File Management System In Java Using Netbeans




if you want the source code click on the download button below

download the source code




Python - Dashboard Form Design Using Tkinter

How To Design a Dashboard Form In Python Tkinter

Design a Dashboard Form In Python Tkinter


In this Python Tutorial we will see How To Design A Dashboard Form In Python Tkinter .

In This Python Tkinter Design Tutorial We Will Use:
- Python Programming Language.
- Tkinter for GUI.
- VsCode IDE.
- flatuicolorpicker.com = to get flat colors.




Project Description And Source Code:

import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image

root = tk.Tk()

# width & height
w = 1050
h = 600

# list of images
pics_list = [
"C:/Users/1BestCsharp/Desktop/images/Buy My Book please.png",
"C:/Users/1BestCsharp/Desktop/images/how to fail at school.png",
"C:/Users/1BestCsharp/Desktop/images/how to lose money.png",
"C:/Users/1BestCsharp/Desktop/images/c# java python.png",
"C:/Users/1BestCsharp/Desktop/images/think inside the box.png",
"C:/Users/1BestCsharp/Desktop/images/life of a tomato.png",
]


mainframe = tk.Frame(root)

#center window
sw = mainframe.winfo_screenwidth()
sh = mainframe.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2
root.geometry('%dx%d+%d+%d' % (w,h,x,y))
#end center window

root.overrideredirect(1) # remove border

frame = tk.Frame(mainframe, bg='#ffffff')
topbarframe = tk.Frame(frame, bg='#636e72', width=w, height=50)
sidebarframe = tk.Frame(frame, bg='#999999', width=250, height=700)
contentframe = tk.Frame(frame, bg='#ffffff', width=900, height=550)

app_title = tk.Label(topbarframe, text='App Dashboard', font=('Helvatica',20,
'underline bold'), bg='#636e72', fg='#ffb229', padx=5)

# create a finction to close the window
def close_dashboard():
root.destroy()

btn_close = tk.Button(topbarframe, text='x',bg='#95a5a6', font=('Verdana',12),
fg='#ffffff', borderwidth=1, relief="solid", command=close_dashboard)

product_frame = tk.Frame(contentframe, bg='#ffb229', width=245, height=150)
product_title = tk.Label(product_frame, text='Products', font=('Verdana',16),
bg='#f69110', fg='#ffffff', width=19, pady=12)
product_count = tk.Label(product_frame, text='199', font=('Verdana',16), bg='#ffb229',
fg='#ffffff', padx=11, pady=10)

customers_frame = tk.Frame(contentframe, bg='#4bc012', width=245, height=150)
customers_title = tk.Label(customers_frame, text='Customers', font=('Verdana',16),
bg='#41a00a', fg='#ffffff', width=19, pady=12)
customers_count = tk.Label(customers_frame, text='441', font=('Verdana',16),
bg='#4bc012', fg='#ffffff', padx=11, pady=10)


sales_frame = tk.Frame(contentframe, bg='#9b59b6', width=245, height=150)
sales_title = tk.Label(sales_frame, text='Sales', font=('Verdana',16), bg='#7d3c9b',
fg='#ffffff', width=19, pady=12)
sales_count = tk.Label(sales_frame, text='2369', font=('Verdana',16), bg='#9b59b6',
fg='#ffffff', padx=11, pady=10)


latestproducts_frame = tk.Frame(contentframe, bg='#2c82c9', width=700, height=265)
latestproducts_title = tk.Label(latestproducts_frame, text='Latest Products',
font=('Verdana',16), bg='#446cb3', fg='#ffffff', width=60, pady=12)
latestproducts_show = tk.Label(latestproducts_frame, bg='#bdc3c7', width=60,
height=265)

# create a function to display images
def displayImages(index):
#global img
img = Image.open(pics_list[index])
img = img.resize((150,200), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
lbl = tk.Label(mainframe)
lbl.image = img
return img

# products
prd1 = tk.Label(latestproducts_show, image = displayImages(0))
prd2 = tk.Label(latestproducts_show, image = displayImages(1))
prd3 = tk.Label(latestproducts_show, image = displayImages(2))
prd4 = tk.Label(latestproducts_show, image = displayImages(3))
prd5 = tk.Label(latestproducts_show, image = displayImages(4))

# menu items
menuitem_1 = tk.Label(sidebarframe, text='Menu Item 1', fg='#ffffff', bg='black',
font=('Verdana',15), padx=5,width=15)
menuitem_2 = tk.Label(sidebarframe, text='Menu Item 2', fg='#ffffff', bg='black',
font=('Verdana',15), padx=5,width=15)
menuitem_3 = tk.Label(sidebarframe, text='Menu Item 3', fg='#ffffff', bg='black',
font=('Verdana',15), padx=5,width=15)
menuitem_4 = tk.Label(sidebarframe, text='Menu Item 4', fg='#ffffff', bg='black',
font=('Verdana',15), padx=5,width=15)
menuitem_5 = tk.Label(sidebarframe, text='Menu Item 5', fg='#ffffff', bg='black',
font=('Verdana',15), padx=5,width=15)
menuitem_6 = tk.Label(sidebarframe, text='Menu Item 6', fg='#ffffff', bg='black',
font=('Verdana',15), padx=5,width=15)
menuitem_7 = tk.Label(sidebarframe, text='Menu Item 7', fg='#ffffff', bg='black',
font=('Verdana',15), padx=5,width=15)
menuitem_8 = tk.Label(sidebarframe, text='Menu Item 8', fg='#ffffff', bg='black',
font=('Verdana',15), padx=5,width=15)
menuitem_9 = tk.Label(sidebarframe, text='Menu Item 9', fg='#ffffff', bg='black',
font=('Verdana',15), padx=5,width=15)
menuitem_10 = tk.Label(sidebarframe, text='Menu Item 10', fg='#ffffff', bg='black',
font=('Verdana',15), padx=5,width=15)

# add hover effect to the menu
menuitem_1.bind("<Enter>", func = lambda e: menuitem_1.config(background='#d35400'))
menuitem_1.bind("<Leave>", func = lambda e: menuitem_1.config(background='black'))

menuitem_2.bind("<Enter>", func = lambda e: menuitem_2.config(background='#d35400'))
menuitem_2.bind("<Leave>", func = lambda e: menuitem_2.config(background='black'))

menuitem_3.bind("<Enter>", func = lambda e: menuitem_3.config(background='#d35400'))
menuitem_3.bind("<Leave>", func = lambda e: menuitem_3.config(background='black'))

menuitem_4.bind("<Enter>", func = lambda e: menuitem_4.config(background='#d35400'))
menuitem_4.bind("<Leave>", func = lambda e: menuitem_4.config(background='black'))

menuitem_5.bind("<Enter>", func = lambda e: menuitem_5.config(background='#d35400'))
menuitem_5.bind("<Leave>", func = lambda e: menuitem_5.config(background='black'))

menuitem_6.bind("<Enter>", func = lambda e: menuitem_6.config(background='#d35400'))
menuitem_6.bind("<Leave>", func = lambda e: menuitem_6.config(background='black'))

menuitem_7.bind("<Enter>", func = lambda e: menuitem_7.config(background='#d35400'))
menuitem_7.bind("<Leave>", func = lambda e: menuitem_7.config(background='black'))

menuitem_8.bind("<Enter>", func = lambda e: menuitem_8.config(background='#d35400'))
menuitem_8.bind("<Leave>", func = lambda e: menuitem_8.config(background='black'))

menuitem_9.bind("<Enter>", func = lambda e: menuitem_9.config(background='#d35400'))
menuitem_9.bind("<Leave>", func = lambda e: menuitem_9.config(background='black'))

menuitem_10.bind("<Enter>", func = lambda e: menuitem_10.config(background='#d35400'))
menuitem_10.bind("<Leave>", func = lambda e: menuitem_10.config(background='black'))

# ------------------------------------ #


mainframe.pack(fill="both", expand=True)

frame.pack(fill="both", expand=True)

topbarframe.pack()
topbarframe.grid_propagate(False)

app_title.place(x=10,y=7)
btn_close.place(x=1010,y=10)

sidebarframe.pack()
sidebarframe.grid_propagate(False)
sidebarframe.place(x=0, y=60)

contentframe.pack()
contentframe.grid_propagate(False)
contentframe.place(x=250, y=50)

product_frame.grid(row=0, column=0, padx=10, pady=10, sticky='nsew')
product_frame.grid_propagate(False)
product_title.grid(row=0, column=0)
product_count.grid(row=1, column=0, padx=15, pady=15)

customers_frame.grid(row=0, column=1, padx=10, pady=10, sticky='nsew')
customers_frame.grid_propagate(False)
customers_title.grid(row=0, column=0)
customers_count.grid(row=1, column=0, padx=15, pady=15)

sales_frame.grid(row=0, column=2, padx=10, pady=10, sticky='nsew')
sales_frame.grid_propagate(False)
sales_title.grid(row=0, column=0)
sales_count.grid(row=1, column=0, padx=15, pady=15)

latestproducts_frame.grid(row=1, column=0, columnspan=3, padx=10, pady=10,
sticky='nsew')
latestproducts_frame.grid_propagate(False)
latestproducts_title.grid(row=0, column=0)
latestproducts_show.grid(row=1, column=0, sticky='nsew')
latestproducts_show.grid_propagate(False)
prd1.grid(row=0, column=0)
prd2.grid(row=0, column=1)
prd3.grid(row=0, column=2)
prd4.grid(row=0, column=3)
prd5.grid(row=0, column=4)


menuitem_1.grid(row=0, column=0, padx=10, pady=10)
menuitem_2.grid(row=1, column=0)
menuitem_3.grid(row=2, column=0, padx=10, pady=10)
menuitem_4.grid(row=3, column=0)
menuitem_5.grid(row=4, column=0, padx=10, pady=10)
menuitem_6.grid(row=5, column=0)
menuitem_7.grid(row=6, column=0, padx=10, pady=10)
menuitem_8.grid(row=7, column=0)
menuitem_9.grid(row=8, column=0, padx=10, pady=10)
menuitem_10.grid(row=9, column=0)

root.mainloop()





Dashboard Form Design in Tkinter




download the source code