Home : Course Map : Chapter 7 : Java : Supplements :
JDialog Subclass
JavaTech
Course Map
Chapter 7

Introduction
Event Overview
Event Processing
Button Events
  Demo 1
 Demo 2
Mouse Events
  Demo3

More Components
  Demo 4  Demo 5
  Demo 6  Demo 7

LayoutManagers-1
  Demo 8     Demo 9
  Demo 10  Demo 11
  Demo 12

LayoutManagers-2
  Demo 13  Demo 14
  Demo 15  Demo 16
  Demo 17

Inner Classes
Anonymous Class
Adapter Classes
  Demo 18  Demo 19
Frames & Menus
  Demo 20  Demo 21
Exercises

    Supplements
AWT Components
  Button
     Demo 1
  Canvas
     Demo 2
  AWT GUI Demo
     Demo 3
Swing Dialogs
JOptionPane Dialog
  Demo 1
JDialog
  Demo 2
UI Enhancement: P1
  Demo 1   Demo 2
  Demo 3

UI Enhancement: P2
  Demo 1
     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

While JOptionPane offers a powerful way to generate basic dialogs, to create more elaborate interactions with the user you will usually find it necessary to subclass JDialog (Java 5.0 Specs). With it you can add multiple components, you can return more than a single value, and you can do checks on the user inputs and inform the user if those inputs need modification.

In the example below, the applet can open a frame, which in turn uses an instance of a JDialog subclass to obtain a URL address from the user. The GetUrlDialog checks the input for proper form before returning to the caller.

Note that here we use an interface to provide the callback mechanism. The frame class implements our TextSetable interface that holds a single method for passing a string. The method includes an integer arguement as well, to identify the particular text.

 
MakeJDialogApplet
MakeJDialogJFrame

GetUrlDialog

TextSetable

 

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
  * This program illustrates the creation of a JDialog subclass.
  * It follows the example of a request to the user to input a URL
  * address.
  *
  * The applet uses a JFrame subclass with a menubar and buttons
  * that can create an instance of GetUrlDialog, which is a subclass
  * of JDialog. It will pass the URL text back to the frame using
  * a method from the TextSetable interface.
 **/
public class MakeJDialogApplet extends JApplet
       implements ActionListener
{
  public void init () {
    Container content_pane = getContentPane ();

    JPanel panel = new JPanel (new BorderLayout ());

    JButton button_open = new JButton ("Open");
    button_open.addActionListener (this);
    panel.add (button_open, "Center");
    content_pane.add (panel);

  } // init

  //  Open the frame
  public void actionPerformed (ActionEvent e ) {
    String command = e.getActionCommand ();
    if (command.equals ("Open")) {
        // Create an instance of the frame and show it.
        MakeJDialogFrame f =  new MakeJDialogFrame (this);
        f.setVisible (true);
    }
  } // actionPerformed

} // class MakeJDialogApplet


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/** This frame uses the TextSetable interface for a call
  * back from the dialog to provide URL text.
 **/
public class MakeJDialogFrame extends JFrame
             implements ActionListener, TextSetable
{
  // Keep a reference to the applet parent.
  MakeJDialogApplet fApplet;
  JLabel fLabel;

  int URL_TEXT = 1;

  /** Create the frame with a couple of buttons and
    * a menubar with one dropdown menu.
   **/
  MakeJDialogFrame (MakeJDialogApplet applet) {
    super ("Frame Test");
    fApplet = applet;

    Container content_pane = getContentPane ();

    // Create a simple interface.
    content_pane.setLayout ( new GridLayout (2,1) );

    content_pane.add (fLabel =
      new JLabel ("http://www.default.com",JLabel.CENTER));

    JPanel panel = new JPanel ();

    JButton button1 = new JButton ("Get URL");
    button1.addActionListener (this);

    JButton button_quit = new JButton ("Quit");
    button_quit.addActionListener (this);

    panel.add (button1);
    panel.add (button_quit);
    content_pane.add (panel);

    // Use the helper method makeMenuItem
    // for making the menu items and registering
    // their listener.
    JMenu m = new JMenu ("Tasks");

    // Menu items for the drop down menu.
    m.add (makeMenuItem ("Get URL"));
    m.add (makeMenuItem ("Quit"));

    JMenuBar mb = new JMenuBar ();
    mb.add (m);

    setJMenuBar (mb);
    pack ();

  } // ctor

  // Override the TextSetable method with this concrete version
  // which gets the URL from the dialog.
  public void setText (int textID, String text) {
    if (textID == URL_TEXT) {
      fLabel.setText (text);
    }
  } // setText

  //
  public void actionPerformed (ActionEvent e) {
    String command = e.getActionCommand ();
    if (command.equals ("Get URL")) {
        // Open a dialog to get the text for a URL
        GetUrlDialog getUrl =
        new GetUrlDialog (this, this, URL_TEXT,
                          fLabel.getText (),
                          true, "Input URL");
    } else if (command.equals ("Quit")) {
        dispose ();
    }
  } // actionPerformed

  // This "helper method" makes a menu item and then
  // registers this applet as a listener to it.
  private JMenuItem makeMenuItem (String name) {
    JMenuItem m = new JMenuItem ( name );
    m.addActionListener ( this );
    return m;
  }

} // class MakeJDialogFrame

/** This interface provides for a callback to pass text. **/
interface TextSetable
{
  /** The textID allows the receiving class to
    * identify what the text represents using its
    * own ID numbering scheme.
   **/
  void setText(int textID, String text);

} // interface TextSetable

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
  * This program illustrates how to create a dialog by
  * subclassing JDialog. Here we use the example of obtaining
  * a URL from the user. Provides a dialog to enter URL
  * for the downloading a story over the web.
**/
public class GetUrlDialog extends JDialog implements ActionListener
{
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++GetUrlDialog+++++++++
  JFrame fParent;

  JTextField fUrlField;
  String fUrlData;

  Container fContainer;
  GridBagLayout fGridBag;
  GridBagConstraints fGBC = new GridBagConstraints ();

  JButton fButtonOK;
  JButton fButtonHelp;

  TextSetable fUrlRequestor; // Use TextSetable interface for callback
  int fTextID = 0; // Type of text

  //-------------------------------------------------------GetUrlDialog---------
  public GetUrlDialog (JFrame frame,
                      TextSetable urlRequestor, int textID,
                      String urlData,
                      boolean modal, String title) {
    // Call the JDialog constructor.
    super (frame, title, modal);
    fUrlData = urlData;
    fParent = frame;

    // Get requestor for call back
    fUrlRequestor = urlRequestor;
    fTextID = textID;

    fContainer = this.getContentPane ();

    // Set the background color of DateDialog.
    fContainer.setBackground (Color.white);

    //  Create a confirmation button.
    fButtonOK = new JButton ("OK");
    fButtonOK.setMnemonic ('O');
    fButtonOK.setPreferredSize (new Dimension (70, 25));
    fButtonOK.addActionListener (this);

    //  Create a cancel button.
    JButton button_cancel = new JButton ("Cancel");
    button_cancel.setMnemonic ('C');
    button_cancel.setPreferredSize (new Dimension (75, 25));
    button_cancel.addActionListener (this);

    //  Create a help button.
    fButtonHelp = new JButton ("Help");
    fButtonHelp.setMnemonic ('H');
    fButtonHelp.setPreferredSize (new Dimension (70, 25));
    fButtonHelp.addActionListener (this);

    //  Create a panel to hold the buttons
    JPanel button_panel = new JPanel ();
    button_panel.setBackground (Color.white);
    button_panel.add (fButtonOK);
    button_panel.add (button_cancel);
    button_panel.add (fButtonHelp);

    //  Use a gridbag layout for the contentpane
    fGridBag = new GridBagLayout ();
    fContainer.setLayout (fGridBag);

    //
    fGBC.fill = GridBagConstraints.BOTH;
    fGBC.gridwidth=6; fGBC.gridheight=1;
    fGBC.weightx=1; fGBC.weighty=1;
    fGBC.insets = new Insets (10,20,10,20);

    addGB (button_panel, 0,1);

    // Give the labels a small weightx and a
    // width of 1 to push them to the left
    fGBC.weightx=0.10; fGBC.weighty=1.0;
    fGBC.gridwidth=1; fGBC.gridheight=1;
    fGBC.insets = new Insets (0,0,0,10);
    JLabel label = new JLabel ("URL",SwingConstants.RIGHT);
    addGB (label,0,0);

    // Give the textfields a large weightx and a
    // width of 5 so they will have a long x width
    fGBC.weightx=1.0; fGBC.weighty=1.0;
    fGBC.insets = new Insets (10,0,10,10);
    fGBC.gridwidth=5; fGBC.gridheight=1;
    fUrlField  = new JTextField ();
    addGB (fUrlField,1,0);

    fUrlField.setText (fUrlData);

    // Resize the dialog box and position it at the center of
    // the applet.
    setSize (300,125);
    Dimension dialogDim = getSize ();
    Dimension frameDim = frame.getSize ();
    Dimension screenSize = getToolkit ().getScreenSize ();
    Point location = frame.getLocation ();
    location.translate (
             (frameDim.width-dialogDim.width)/2,
             (frameDim.height-dialogDim.height)/2);
    location.x = Math.max ( 0, Math.min (location.x,
                             screenSize.width-getSize ().width));
    location.y = Math.max (0, Math.min (location.y,
                             screenSize.height-getSize ().height));

    setLocation (location.x, location.y);

    setVisible (true);
  } // ctor

  //-------------------------------------------------------addGB----------------
  public void addGB (Component component, int x, int y) {
    fGBC.gridx=x; fGBC.gridy = y;
    fGridBag.setConstraints (component, fGBC);
    fContainer.add (component);
  } // addGB

  //-------------------------------------------------------actionPerformed------
  /** When the OK button on the dialog box is clicked. **/
  public void actionPerformed (ActionEvent e) {
    if (e.getSource () == fButtonOK)  {
        fUrlData = fUrlField.getText ().trim ();

        // Check the entry for proper length and form.
        if (fUrlData.length () == 0) {
            JOptionPane.showMessageDialog (null,
               "Empty URL entry!", "Input Error",
            JOptionPane.ERROR_MESSAGE);
            return;
        }

        // Use the URL class to determine if the URL
        // entry is in proper form.
        try {
          java.net.URL url = new java.net.URL (fUrlData);
        }
        catch (java.net.MalformedURLException ex) {
           JOptionPane.showMessageDialog (null,
             "Malformed URL entry!", "Input Error",
              JOptionPane.ERROR_MESSAGE);
           return;
        }

        // Pass the URL back to the caller. Use the fTextID
        // number to let caller know what type of text is being
        // passed.
        fUrlRequestor.setText (fTextID, fUrlData);

    } else if (e.getSource () == fButtonHelp) {
        JOptionPane.showMessageDialog (null,
                   "Help message...");
        return; // Don't close dialog
    }
    // Close dialog after OK or Cancel button clicked
    this.dispose ();
  } // actionPerformed

} // GetUrlDialog

 

References & Web Resources

Latest update: Nov. 4, 2004

           Tech
Histogram UI
  Demo 1
Probablity Distrib.
  Demo 2 Demo 3
RejectionMethod
Histogram Stats
  Demo 4
Exercises

           Physics
Sim & Randomness
Custom Prob. Dist.
   Demo 1
Histogram Dist.
   Demo 2
Monte Carlo
  Demo 3
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.