Dialog Box
--> Dialog box is a window like frame, however, it contains only close (x) button
i.e it does not have maximize and minimize buttons.
--> A dialog box can be built-in/library dialog box(message dialog, confirm dialog,
input dialog, file dialog, print dialog, font dialog, color dialog) or it can be
user defined dialog box.
--> For creating user defined dialog box(custom dialog box) we use JDialog class.
Its constructors are:
a. JDialog(JFrame parent)
b. JDialog(JFrame parent, boolean isModal)
c. JDialog(JFrame parent, String title, boolean isModal)
Note: A dialog box can be modal or non-modal.
1. Modal Dialog Box: A dialog box which does not allow to access the features of
its parent application until it is closed is called modal dialog box.
2. Non-Modal Dialog Box: A dialog box which allows to access the features of its
parent application before it is closed is called non-modal dialog box.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyFrame implements ActionListener{
JFrame f1;
JButton b1;
MyFrame() {
f1 = new JFrame();
f1.setSize(500, 500);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setLayout(new FlowLayout());
b1=new JButton("About Us");
f1.add(b1);
b1.addActionListener(this);
f1.setVisible(true);
public static void main(String[] args) {
MyFrame ob = new MyFrame();
}
public void actionPerformed(ActionEvent e){
JDialog d1=new JDialog(f1,true);
d1.setSize(300,300);
d1.setLayout(new FlowLayout());
JLabel L1=new JLabel("Contact Us At: abc@gmail.com");
d1.add(L1);
d1.setVisible(true);
}
}
------------------------------------------------------------------
Using message, input and confirm dialog
--------------------------------------
import javax.swing.JOptionPane;
public class TestDialog {
public static void main(String[] args) {
//input dialog
int a=Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));
if(a%2==0)
//message dialog
JOptionPane.showMessageDialog(null,"Even");
else
//message dialog
JOptionPane.showMessageDialog(null,"Odd");
//confirm dialog
int choice= JOptionPane.showConfirmDialog(null,"Are you sure??");
if(choice==0)
JOptionPane.showMessageDialog(null,"You chose Yes");
else if(choice==1)
JOptionPane.showMessageDialog(null,"You chose No");
else if(choice==2)
JOptionPane.showMessageDialog(null,"You chose Cancel");