Java show simple open file dialog using jfilechooser

In Java Swing, you can use the JFileChooser component to display an "Open" dialog to the user and allow them to select a file. Here's an example of how to do this:

refe‮t r‬o:theitroad.com
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileNameExtensionFilter;

public class OpenFileDialogExample extends JFrame {

    public OpenFileDialogExample() {
        super("Open File Dialog Example");

        // Create a new file chooser
        JFileChooser fileChooser = new JFileChooser();

        // Set the file chooser to display only files with the .txt extension
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
        fileChooser.setFileFilter(filter);

        // Display the "Open" dialog
        int result = fileChooser.showOpenDialog(this);

        // If the user clicked "Open"
        if (result == JFileChooser.APPROVE_OPTION) {
            // Get the selected file
            java.io.File file = fileChooser.getSelectedFile();

            // Do something with the file, like reading from it
            // ...

            System.out.println("Selected file: " + file.getAbsolutePath());
        }

        // Set the size, location and visibility of the frame
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new OpenFileDialogExample();
    }
}

In this example, we create a JFileChooser component and set its file filter to allow only files with the .txt extension. We then display the "Open" dialog using the showOpenDialog method and wait for the user to select a file. If the user clicks "Open", we retrieve the selected file using the getSelectedFile method and do something with it, like reading from it.

Note that the showOpenDialog method is a blocking call, so the code after it won't be executed until the user selects a file or cancels the dialog.

When you run this example, an "Open" dialog will be displayed to the user, and they will be able to select a file. If they select a file and click "Open", the file's path will be printed to the console. If they cancel the dialog, nothing will happen.