Create a backup dialog with JFileChooser
We have seen how to open a file with JFileChooser, Now, to bring up the dialog box to save a file in Java, we need to invoke the method showSaveDialog of the JFileChooser class. The save dialog box looks exactly like the one on the opening, except for the window title and the text of the button to approve the operation.The save dialog is displayed with these two lines of code:
//instantiate JFileChooser
final JFileChooser fc = new JFileChooser();
//invoke the showSaveDialog method
int valueour = fc.showSaveDialog(window);
The JFileChooser instance is the same for opening and saving dialogs, so you must use the same instance. File chooser and avoid creating multiple versions.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class SaveDialog {
public static void main(String[] args) {
final JFrame window = new JFrame();
window.setSize(200,200);
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
JMenuBar jmb = new JMenuBar();
JMenu jm = new JMenu("Ficher");
JMenuItem Save = new JMenuItem("Save");
jm.add(Save);
jmb.add(jm);
window.add(jmb,BorderLayout.NORTH);
JFileChooser fc = new JFileChooser();
Save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
int val_retour = fc.showSaveDialog(window);
if (val_retour == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//display the absolute path of the file
System.out.println("Absolute path: "+file.getAbsolutePath()+"\n");
} else {
System.out.println("Registration is canceled\n");
}
}
});
}
}
The console:
Absolute path: C:\Users\VAIO\Documents\CC++\test.txtYou can change the file selection mode. For example, the following line of code makes it possible to select only the folders in JFileChooser:
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);Another selection mode is FILES_AND_DIRECTORIES. The default setting is FILES_ONLY.
References
Oracle Doc:How to Use File Choosers
StackOverFlow:How to save a file using JFileChooser.showSaveDialog?