Dialog Box in Java with Examples [ Open and Save Dialog Box ]

Dialog Box in Java with Examples

explore java logo

Table of Contents

a) Introduction to Dialog Box
b) Types of Dialog Box
c) How to create Dialog Box?
d) Modal and Non-Modal Dialog Box
e) Example of Dialog Box with Source Code and Output 
f) Introduction to Open and Save Dialog Box
g) How to use JFileChooser Class ?
h) Example with Source Code
i) Output

*******************

Introduction:
A Dialog Box is a window like frame, however it does not contain menu bar and it cannot execute independently i.e. it needs parent frame to execute. A dialog box is a prompt window. A Dialog Box can be built-in dialog box such as message dialog, confirm dialog, input dialog , save dialog, open dialog or user defined dialog box.
The built-in dialog box like confirm dialog, input dialog and message dialog, JOptionPane class is used. Similarly, the other built-in dialog box like save dialog and open dialog, JFileChooser class is used.

How to create the user defined Dialog Box?

To create the user defined dialog box, we should use JDialog class. JDialog class consists of two constructor, they are;

JDialog(JFrame parent, boolean isModal)
JDialog(JFrame parent, String title, boolean isModal)

The above both constructors are used to create the user defined dialog box. The difference that you can see is that in first constructor, title of dialog box cannot be given but in the second constructor, we can give title to the dialog box.

Modal and Non-Modal Dialog Box:

Modal Dialog Box:
It is a type of dialog box which does not allow to access other parts of application until it is closed. It means the other function of the application is not allowed We pass value ‘true’ for isModal in the constructor to make a modal dialog box.

Non-Modal Dialog Box:
It is a type of dialog box which allows to access the other parts of the application before it is closed. It means that we can use the application and their function even if we does not close the dialog box. We pass value ‘false’ for isModal in the constructor to make a non-modal dialog box.

Examples;

Let us create a built-in message 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.*;
import java.awt.*;
import java.awt.event.*;
public class DialogBoxDemo implements ActionListener {
    JFrame f;
    JButton b;
    DialogBoxDemo(){
        f=new JFrame("Built-in Dialog Box");
        f.setSize(400, 300); //setting the size of frame
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setLayout(new FlowLayout()); //setting layout
       
        b=new JButton("Show Message Dialog");
        //registering the event
        b.addActionListener(this);
        //adding components to the frame
        f.add(b);
        f.setVisible(true);
    }
   
    //main method
    public static void main(String[] args) {
         //calling constructor
        new DialogBoxDemo();
    }
   
    //overriding method of ActionListener
  public void actionPerformed(ActionEvent e){
      /* since there is single button so we can
      directly write the code without checking
      which buton is clicked */
     
      JOptionPane.showMessageDialog(f, "This is a Message Dialog");
     
  } 
}

Output:
The image below is the initial output when you first run the program.
Dialog Box in Java with Examples


And after you click the button then message dialog box will be shown.

Dialog Box in Java with Examples

Similarly for other built-in dialog like input dialog and confirm dialog, you can try it in your own.

The other built-in dialog box like open dialog and save dialog is discussed below:

**************************

Introduction:
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
import java.io.File;
public class OpenAndSaveDialogBoxDemo implements ActionListener {
    JFrame f;
    JButton b1,b2;
  
    //creating constructor

    OpenAndSaveDialogBoxDemo(){
        f=new JFrame("Built-in Dialog Box");
        // set size of the frame
        f.setSize(400, 300);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // set layout
        f.setLayout(new FlowLayout());
       
 
        b1=new JButton("Open");
     
        b2=new JButton("Save");
        
        // register the action event
        b1.addActionListener(this);
        b2.addActionListener(this);
       
       
        f.add(b1);
       
        f.add(b2);
       
        f.setVisible(true);
       
    }
   
    //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
        if(e.getSource()==b1){
            JFileChooser jfc=new JFileChooser();
            jfc.setDialogTitle("Open File");
            int result = jfc.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
                     File selectedFile = jfc.getSelectedFile();
                                        System.out.println(""+selectedFile.getAbsolutePath());
                      
                }
        }
        //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();
                System.out.println(file);   
            }
        }
    }
   
}

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

Output:
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

Previous Post Next Post