Don’t change filename textfield when a directory is selected in a JFileChooser

Here’s some code that solves that problem.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.io.*;
 
public class Main extends JFrame
{
   private String fileSelected = "autoexec.bat";
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
  
   public Main() {
      JButton fileButton = new JButton("Select File");
      fileButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            File file = getFileFromUser();
            if (file != null)
               System.out.println(file.getName());
         }
      });
      getContentPane().add(fileButton);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      pack();
   }
  
   public File getFileFromUser() {
      JFileChooser fc = new JFileChooser();
 
      // use current directory
      fc.setCurrentDirectory(new File("c:\"));
 
      // set default name
      fc.setSelectedFile(new File(fileSelected));
 
      fc.addPropertyChangeListener(new PropertyChangeListener() {
         public void propertyChange(PropertyChangeEvent pce) {
            String property = pce.getPropertyName();
            if (property.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
               File dir = (File) pce.getNewValue();
               if (dir.isDirectory()) {
                  ((JFileChooser) pce.getSource()).setSelectedFile(new File(dir, fileSelected));
               }
               else {
                  fileSelected = ((JFileChooser) pce.getSource()).getSelectedFile().getName();
               }
            }
            else if (property.equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
               File dir = (File) pce.getNewValue();
               ((JFileChooser) pce.getSource()).setSelectedFile(new File(dir, fileSelected));
            }
         }
      });
 
      // show dialog for opening files
      int result = fc.showSaveDialog(this);
 
      if (result != fc.APPROVE_OPTION) 
         return null;
       
      return fc.getSelectedFile();
   }
}