Search this site:       RSS Feeds        Facebook
Submit to DeliciousSubmit to DiggSubmit to FacebookSubmit to Google BookmarksSubmit to StumbleuponSubmit to TechnoratiSubmit to TwitterSubmit to LinkedIn

Show save file dialog using JFileChooser

Most Recommended Books:      Effective Java      Thinking in Java      Head First Java      Head First Servlets and JSP

Swing provides class javax.swing.JFileChooser that can be used to present a dialog for user to choose a location and type a file name to be saved, using showSaveDialog() method. Syntax of this method is as follows:

        public int showSaveDialog(Component parent)

where parent is the parent component of the dialog, such as a JFrame. Once the user typed a file name and select OK or Cancel, the method returns one of the following value:

    • JFileChooser.CANCEL_OPTION : the user cancels file selection.
    • JFileChooser.APPROVE_OPTION: the user accepts file selection.
    • JFileChooser.ERROR_OPTION: if there’s an error or the user closes the dialog by clicking on X button.

After the dialog is dismissed and the user approved a selection, use the following methods to get the selected file:

    • File getSelectedFile()

Before calling showSaveDialog() method, you may want to set some options for the dialog:

    • setDialogTitle(String) sets a custom title text for the dialog.
    • setCurrentDirectory(File) sets the directory where will be saved.

Following is an example code:

// parent component of the dialog
JFrame parentFrame = new JFrame();

JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");    

int userSelection = fileChooser.showSaveDialog(parentFrame);

if (userSelection == JFileChooser.APPROVE_OPTION) {
    File fileToSave = fileChooser.getSelectedFile();
    System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}

And following is a screenshot of the dialog:

save file dialog

You can download a fully working example code in the attachment section.


Ads: Get 25% OFF when registering any hosting account at www.hostgator.com with our coupon code: CODEJAVA25
Submit to DeliciousSubmit to DiggSubmit to FacebookSubmit to Google BookmarksSubmit to StumbleuponSubmit to TechnoratiSubmit to TwitterSubmit to LinkedIn
Attachments:
Download this file (SaveFileDialogExample.java)SaveFileDialogExample.java[source code]1 Kb

Additional information