Dialog Box in Java with Examples
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.
And after you click the button then message dialog
box will be shown.
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:
**************************
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
    // set size of the frame
       f.setSize(400,
300);
      Â
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    // set layout
    // set layout
       f.setLayout(new
FlowLayout());
      Â
Â
       b1=new
JButton("Open");
    Â
       b2=new
JButton("Save");
    Â
    // register the action event
    // 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
// 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:
Output:
The image below is the initial output when you run
the program from above source code.
When you click to the Open button the open dialog
box will appear.
Similarly when you click to the Save button the save
dialog box will appear.
Now let’s move on the next lesson about user defined
dialog box.