Java file picker component in swing

In Java Swing, you can use the JFileChooser component to create a file picker dialog that allows the user to select a file or directory.

Here's an example of how to use JFileChooser to create a file picker dialog:

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FilePickerExample {
    public static void main(String[] args) {
        // Create a file picker dialog
        JFileChooser fileChooser = new JFileChooser();
        
        // Set the default directory for the file picker
        fileChooser.setCurrentDirectory(new java.io.File("."));
        
        // Add a filter to only display text files
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
        fileChooser.setFileFilter(filter);
        
        // Display the file picker dialog
        int result = fileChooser.showOpenDialog(new JFrame());
        
        // If the user selected a file, get the file path and display it
        if (result == JFileChooser.APPROVE_OPTION) {
            String filePath = fileChooser.getSelectedFile().getAbsolutePath();
            System.out.println("Selected file: " + filePath);
        }
    }
}
Sourc‮.www:e‬theitroad.com

In this example, we create a JFileChooser object and set the default directory to the current directory. We also add a file filter to only display text files.

To display the file picker dialog, we call the showOpenDialog() method on the JFileChooser object and pass in a JFrame instance. This method blocks until the user selects a file or cancels the dialog.

If the user selects a file, we get the absolute file path using the getAbsolutePath() method of the selected file and display it.

Note that JFileChooser also provides other methods for configuring the file picker dialog, such as setting the dialog title, allowing multiple file selection, and specifying whether to display files or directories.