Java JFileChooser CANCEL_OPTION

Syntax

JFileChooser.CANCEL_OPTION has the following syntax.

public static final int CANCEL_OPTION

Example

In the following code shows how to use JFileChooser.CANCEL_OPTION field.


/* w w w . ja v  a 2s .  co  m*/
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JLabel;

public class Main {

  public static void main(String[] a) {
    JFileChooser fileChooser = new JFileChooser(".");
    fileChooser.setAccessory(new LabelAccessory(fileChooser));
    int status = fileChooser.showOpenDialog(null);
    if (status == JFileChooser.APPROVE_OPTION) {
      File selectedFile = fileChooser.getSelectedFile();
      System.out.println(selectedFile.getParent());
      System.out.println(selectedFile.getName());
    } else if (status == JFileChooser.CANCEL_OPTION) {
      System.out.println("JFileChooser.CANCEL_OPTION");
    }
  }
}

class LabelAccessory extends JLabel implements PropertyChangeListener {

  public LabelAccessory(JFileChooser chooser) {
    chooser.addPropertyChangeListener(this);
    setPreferredSize(new Dimension(100, 100));
  }

  public void propertyChange(PropertyChangeEvent changeEvent) {
    String changeName = changeEvent.getPropertyName();
    if (changeName.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
      File file = (File) changeEvent.getNewValue();
      if (file != null) {
        setText(file.getName());
      }
    }
  }
}