Use a file dialog to open a file from a local drive

The example shows the integration of a javax.swing.JFileChooser in a processing applet.

Download the source file

Table Of Contents

Source - applet JFileChooserExample


/**
* Demonstration of JFileChooser opened from Processing
* A running PApplet opens a JFileChooser to load a background image
* on keyPressed()
*
* by georg munkel
**/


// import the JFileChooser from swing library
import javax.swing.JFileChooser;

//the backgroundImage
PImage bgImage = null;


void setup()
{
        //do your inital tasks here
}

void draw()
{
        //check if the background images is loaded yet
        if (bgImage != null)
        {
                //display the streched image
                image(bgImage, 0, 0, width, height);
        }

        //do some graphics here
        ellipse( random(width), random(height), 10, 10);
}


void keyPressed()
{
        //get the file name with path from loadAFile()
        String file = loadAFile();

        //try to load an image file from the given file name
        if (file != null) bgImage = loadImage(file);
}


/**
* opens a JFileChooser to select a file
* returns the file name with complete path as String
*         null, if no file was selected
**/
String loadAFile()
{
        //file name to be returned by this method
        String fileWithPath = null;

        //switch of the loop of the draw method
        //importand!! otherwise the applet will crash
        noLoop();

        //create a new instance of JFileChooser 'chooser'
        JFileChooser chooser = new JFileChooser();

        //store the state of the file chooser on popdown in returnVal
        //check out showSaveDialog!
        //see: http://java.sun.com/javase/6/docs/api/index.html?javax/swing/JFileChooser.html
        //              hand over the applet (this) a parent component for chooser
        int returnVal = chooser.showOpenDialog( this );

        //check the value of returnVal
        if(returnVal == JFileChooser.APPROVE_OPTION)
        {
                //a file has been selected
                System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());

                //set the return varliable to the file name with path
                fileWithPath = chooser.getSelectedFile().getAbsolutePath();
        }

        //the file dialog is closed again
        //so switch on draw method loop again
        loop();
        //and return the fileName
        return fileWithPath;
}

This website has been archived and is no longer maintained.