|
A common need is to prompt the user for a file -- either to open, or to
create. This is the function of the JFileChooser dialog.
Opening a File
package swingExamples;
import java.io.File;
import javax.swing.JFileChooser;
public class ChooseFile
{
public static void main(String[] args)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(
new File(".") // Current directory
);
int result = fileChooser.showOpenDialog(
null // parent component
);
if (result == JFileChooser.CANCEL_OPTION)
{
System.out.println("You hit Cancel");
}
else if (result == JFileChooser.APPROVE_OPTION)
{
System.out.println("You selected a file");
}
}
}
|
which produces the following dialog:

Saving a File
If you want to select a file for saving:
package swingExamples;
import java.io.File;
import javax.swing.JFileChooser;
public class SaveFile1
{
public static void main(String[] args)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(
new File(".") // Current directory
);
int result = fileChooser.showSaveDialog(
null // parent component
);
if (result == JFileChooser.CANCEL_OPTION)
{
System.out.println("You hit Cancel");
}
else if (result == JFileChooser.APPROVE_OPTION)
{
System.out.println("You selected a file");
}
}
}
|
which produces:

Discovering What the User Selected
How do you discover what the user selected? Here's an example:
package swingExamples;
import java.io.File;
import javax.swing.JFileChooser;
public class SaveFile2
{
public static void main(String[] args)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(
new File(".") // Current directory
);
int result = fileChooser.showSaveDialog(
null // parent component
);
if (result == JFileChooser.CANCEL_OPTION)
{
System.out.println("You hit Cancel");
}
else if (result == JFileChooser.APPROVE_OPTION)
{
System.out.println("You selected a file");
File file = fileChooser.getSelectedFile();
System.out.println(
"File selected is: " + file.getAbsoluteFile());
}
}
}
|
which outputs the following, once the user has selected a file and clicked
on the appropriate button:
You selected a file
File selected is: C:\...\Play\bleye.gif
|