All Posts

Java Swing JFileChooser

Java Swing JFileChooser

In this tutorial, we will learn about the Java Swing JFileChooser class. The file chooser dialog box is a GUI component used for navigating the file system on the user machine.

Swing JFileChooser

We can use the file chooser to choose the files. We can import the class into the Java program

import javax.swing.JFileChooser;

We can create an instance of the JFileChooser class by using the following statement::

JFileChooser fileChooser = new JFileChooser();

Java Program

package com.testingdocs.swing.components;

import java.awt.event.*;
import java.io.*;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**********************************************
 * FileName: FileChooseDemo.java
 * Package : com.testingdocs.swing.components
 * 
 * Java Tutorials - www.TestingDocs.com
 **********************************************/

public class FileChooseDemo {

    public static void main(String[] args) {
        JFrame frame = new JFrame("JFileChoose - www.TestingDocs.com");

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setMultiSelectionEnabled(true);

        JButton btn = new JButton("Show Dialog");
        btn.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                int retVal = fileChooser.showOpenDialog(frame);
                if (retVal == JFileChooser.APPROVE_OPTION) {
                    File[] selectedfiles = fileChooser.getSelectedFiles();
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < selectedfiles.length; i++) {
                        sb.append(selectedfiles[i].getName() + "\n");
                    }
                    JOptionPane.showMessageDialog(frame, sb.toString());
                }

            }
        });
 
        // Create Panel instance
        JPanel panel = new JPanel();
        panel.add(btn);
        
        // Frame settings
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.getContentPane().add(panel);
        frame.setVisible(true);
    }
}

Output

Run the program to view the output.

 

JFileChooser Class

—

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/