Description:
Using JFileChooser in Java involves creating an instance to allow users to select files or directories through a graphical interface. A JFileChooser instance is typically initialized with the default or a specific directory path. Calling its showOpenDialog or showSaveDialog methods opens a dialog for selecting files or saving them, returning an integer value indicating the user's choice, such as APPROVE_OPTION or CANCEL_OPTION. The selected file's path is obtained using the getSelectedFile method. Customization options like file filters can restrict which files appear in the dialog, improving user experience.
Sample Source Code
# FileChooserExample.java
package JavaSamples;
import javax.swing.*;
import java.io.File;
public class FileChooserExample {
public static void main(String[] args) {
JFrame frame = new JFrame("File Chooser Example");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
JOptionPane.showMessageDialog(frame, "Selected file: " + selectedFile.getAbsolutePath());
} else {
JOptionPane.showMessageDialog(frame, "No file selected.");
}
}
}