Listening for Changes to the Selected File in a JFileChooser Dialog - Java Swing

Java examples for Swing:JFileChooser

Description

Listening for Changes to the Selected File 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[] argv) throws Exception {
    JFileChooser chooser = new JFileChooser();

    chooser.addPropertyChangeListener(new PropertyChangeListener() {
      public void propertyChange(PropertyChangeEvent evt) {
        if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt
            .getPropertyName())) {//w ww .  j a v a  2s.  c o m
          JFileChooser chooser = (JFileChooser) evt.getSource();
          File oldFile = (File) evt.getOldValue();
          File newFile = (File) evt.getNewValue();

          // The selected file should always be the same as newFile
          File curFile = chooser.getSelectedFile();
        } else if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(evt
            .getPropertyName())) {
          JFileChooser chooser = (JFileChooser) evt.getSource();
          File[] oldFiles = (File[]) evt.getOldValue();
          File[] newFiles = (File[]) evt.getNewValue();

          File[] files = chooser.getSelectedFiles();
        }
      }
    });
  }
}

Related Tutorials