Creating a directory chooser

Set the file selection mode in JFileChooser to JFileChooser.DIRECTORIES_ONLY. A directory
can then be selected by not navigating into the directory but by selecting it when you’re a level
higher.

Main.java:

import javax.swing.filechooser.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame {
   public Main() {
      super("JFileChooser Directory Chooser Demonstration");
 
      getContentPane().setLayout(new FlowLayout()); 
      JButton button = new JButton("Show JFileChooser and select directory");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int r = fc.showOpenDialog(Main.this); 
            while (r != JFileChooser.APPROVE_OPTION) {
               JOptionPane.showMessageDialog(Main.this,"Try again, select a directory.", 
                  "ERROR", JOptionPane.ERROR_MESSAGE); 
               r = fc.showOpenDialog(Main.this); 
            }
  
            System.out.println("Selected directory: " + fc.getSelectedFile());
         }
      });
 
      getContentPane().add(button); 
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}