Open and Save Dialog Box in Java - JFileChooser Class with Example

Open and Save Built-in Dialog Box in Java using JFileChooser class with Example

beginning with programming logo

Table of Contents

a) Introduction to Open and Save Dialog Box
b) How to use JFileChooser Class ?
c) Example with Source Code
d) Output


Open and Save dialog box are also built-in dialog box which comes under the JFileChooser class. These both dialog box seems to be similar but there is a difference between them.

Open Dialog box uses showOpenDialog() method.  This method makes you to choose the pre-existing file and also it allows you to delete or over-write the file.

Similarly, Save Dialog Box uses showSaveDialog() method. This methods creates a new file if existing file is not found.

Let us see the example of Open Dialog box and Show Dialog box;
Source code:

 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.

 * @author AnkitPC
import javax.swing.*; //for components
import java.awt.*; //for layout
import java.awt.event.*; //for event handling
public class OpenAndSaveDialogBoxDemo implements ActionListener {
    JFrame f;
    JButton b1,b2;
    //creating constructor

        f=new JFrame("Built-in Dialog Box");
        // set size of the frame
        f.setSize(400, 300);
        // set layout
        f.setLayout(new FlowLayout());
        b1=new JButton("Open");
        b2=new JButton("Save");
        // register the action event
    //main method
    public static void main(String[] args) {
        //call constructor
        new OpenAndSaveDialogBoxDemo();
// overriding the method of action listener interface
// perform some actions when button is clicked
    public void actionPerformed(ActionEvent e){
        //check if it is open button
            JFileChooser jfc=new JFileChooser();
            jfc.setDialogTitle("Open File");
            int result = jfc.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
                     File selectedFile = jfc.getSelectedFile();
        //check if it is save button
        else if(e.getSource()==b2){
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Specify a file to save");  

            int userSelection = fileChooser.showSaveDialog(f);

            if (userSelection == JFileChooser.APPROVE_OPTION) {
                File file=fileChooser.getSelectedFile();

Note: The highlighted words in the source code are the comments.

The image below is the initial output when you run the program from above source code.
open and save dialog box

When you click to the Open button the open dialog box will appear.

open dialog box

Similarly when you click to the Save button the save dialog box will appear.

save dialog box

Now let’s move on the next lesson about user defined dialog box.


Post a Comment