Creating a JDialog -- Simplified Example

In this example i am going to simplify creating a JDialog. There are 15 constructors in JDialog class which creates a terror for a starter. Don't worry, it is so simple and I'll show how to create a JDialog in the most easiest way possible. Before we look into the example, let us recall that JDialog is a sub class of java.awt.Dialog so all the methods in this are inherited to JDialog.

import javax.swing.*;
import java.awt.*;
class JDialogExample extends JFrame
{
JDialog d1;

    public JDialogExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JDialog Example");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        // Must be called before creating JDialog for
        // the desired effect
        JDialog.setDefaultLookAndFeelDecorated(true);
       
        // A perfect constructor, mostly used.
        // A dialog with current frame as parent
        // a given title, and modal
        d1=new JDialog(this,"This is title",true);
       
        // Set size
        d1.setSize(400,400);
       
        // Set some layout
        d1.setLayout(new FlowLayout());
       
        d1.add(new JButton("Button"));
        d1.add(new JLabel("Label"));
        d1.add(new JTextField(20));
       
        setSize(400,400);
        setVisible(true);
       
        // Like JFrame, JDialog isn't visible, you'll
        // have to make it visible
        // Remember to show JDialog after its parent is
        // shown so that its parent is visible
        d1.setVisible(true);
    }
   
    public static void main(String args[])
    {
        new JDialogExample();
    }
}

Screenshot of JDialog Example

No comments: