Listening for Changes to the Current Directory in a JFileChooser Dialog - Java Swing

Java examples for Swing:JFileChooser

Description

Listening for Changes to the Current Directory in a JFileChooser Dialog

Demo Code

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

import javax.swing.JFileChooser;

public class Main {
  public static void main(String[] args) {
    final JFileChooser chooser = new JFileChooser();

    // Add listener on chooser to detect changes to current directory
    chooser.addPropertyChangeListener(new PropertyChangeListener() {
      public void propertyChange(PropertyChangeEvent evt) {
        if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
          JFileChooser chooser = (JFileChooser) evt.getSource();
          File oldDir = (File) evt.getOldValue();
          File newDir = (File) evt.getNewValue();

          // The current directory should always be the same as newDir
          File curDir = chooser.getCurrentDirectory();
        }//from   ww w. j a  v  a 2 s.co m
      }
    });
  }
}

Related Tutorials