Chapter 24

Dialog Boxes


CONTNETS

In most cases, you'll add controls to your applet's display in order to present information to the user or to obtain information from the user. However, there may be times when you prefer to create a dialog box. For example, when the applet encounters some sort of error, a pop-up dialog box not only supplies the user with important information, but also immediately draws his attention to that information. Although Java supports dialog boxes, they unfortunately can only be associated with a frame window. This requirement limits their usefulness, but you still may want to use a dialog box at one time or another. In this chapter, you'll see how.

Using a Dialog Box

To create, display, and handle a dialog box, you must perform the following steps:

  1. Create the dialog box object.
  2. Create and set a layout manager for the dialog box.
  3. Create controls and add them to the dialog box.
  4. Call the dialog's show() method to display the dialog box.
  5. When the user clicks the OK or Cancel button, call the dialog's hide() method to remove the dialog box from the screen.
  6. Extract and process the data, if any, entered into the dialog box's controls.

The following section discuss the above steps in greater detail.

Creating the Dialog Box

Java's dialog boxes are objects of the Dialog class. So, to create a dialog box object, you first call the Dialog class's constructor, like this:


Dialog dialog = new Dialog(frame, title, modal);

The constructor's three arguments refer to a frame window, the dialog box's title, and boolean value indicating whether the dialog box is modal (true) or modeless (false). A modal dialog box, which is the most common of the two types, retains the focus until the user dismisses it. This forces the user to respond to the dialog box before continuing with the program. A modeless dialog box can lose the focus to another window, which means that the user can switch to another window even while the dialog box is still on the screen.

NOTE
Although Java claims to support both modal and modeless dialog boxes, the constructor's argument doesn't seem to make any difference. In my experience, every Java dialog box is modeless. Maybe this inconsistency will be corrected by the time you read this book.

Creating the Dialog Box's Layout

Once you have the dialog box object created, you must give it a layout manager. If you fail to do this, any components you try to place in the dialog box will not appear. You perform this step exactly as you would for any other type of window or applet, by creating and setting the layout object:


FlowLayout layout = new FlowLayout();

dialog.setLayout(layout);

The next step is to create and add whatever controls you want to appear in the dialog box. You'll always have at least an OK button, with which the user can dismiss the dialog box:


Button button = new Button("OK");

dialog.add(button);

Displaying the Dialog Box

Just like a frame window, a dialog box doesn't appear on the screen until you call its show() method, like this:


dialog.show();

Once the dialog box is on the screen, the user can manipulate its controls in order to enter information into the dialog box's fields or to dismiss the dialog box from the screen.

Removing the Dialog Box

When the user clicks a dialog box's OK or Cancel buttons, that's your applet's signal to remove the dialog box from the screen, which you do by calling its hide() method:


dialog.hide();

The hide() method removes the dialog box from the screen, but the dialog box and its controls remain in memory so that you can access them in order to extract whatever information the user may have entered into the dialog box.

After you've removed the dialog box from the screen, you can use a control's methods to extract whatever information the user may have entered into the dialog's controls. For example, to get the entry from a text field control, you'd call the control's getText() method.

Methods of the Dialog Class

Like any class, Dialog provides a set of public methods that you can use to control the dialog box. Dialog also inherits many methods from its superclasses, Window and Container. Table 24.1 lists the most useful methods of the Dialog class, including those methods inherited from the Window and Container classes.

Table 24.1  Useful Methods of the Dialog Class (Including Inherited).

MethodDescription
Component add(Component comp) Adds a component to the dialog box.
void dispose()Removes the dialog box from memory.
LayoutManager getLayout()Returns the dialog's layout manager.
String getTitle()Returns the dialog box's title.
void hide()Removes the dialog box from the screen.
Boolean isModal()Returns true if the dialog box is modal.
Boolean isResizable()Returns true if the dialog box is resizable.
Component locate(int x, int y) Returns the component at the given location.
void remove(Component comp)Removes a component from the dialog box.
void removeAll()Removes all components.
void setLayout(LayoutManager mgr) Sets the dialog's layout manager.
void setResizable(booleanSets the resizable attribute.resizable)
void setTitle(String title)Sets the dialog box's title.
void show()Displays the dialog box.

Example: A Dialog Box for Text Input

Your last task in this chapter is to put your newly acquired knowledge of dialog boxes to work. Listing 24.1 is an applet that enables you to display a frame window. From the frame window's menu bar, you can select a command that displays a dialog box. This dialog box contains an OK button for dismissing the dialog box and a text field for entering information. When you dismiss the dialog box, the text you entered into the text field control appears in the frame window. Figure 24.1 shows the applet, the frame window, and the dialog box.

Figure 24.1 : This is DialogApplet running under Appletviewer.


Listing 24.1  DialogApplet.java: An Applet That Displays a Dialog Box.

import java.awt.*;

import java.applet.*;



public class DialogApplet extends Applet

{

    DialogFrame frame;

    Button button;



    public void init()

    {

          frame = new DialogFrame("Dialog Window");



          button = new Button("Show Window");

          add(button);

    }





    public boolean action(Event evt, Object arg)

    {

        boolean visible = frame.isShowing();

        if (visible)

        {

            frame.hide();

            button.setLabel("Show Window");

        }

        else

        {

            frame.show();

            button.setLabel("Hide Window");

        }



        return true;

    }

}



class DialogFrame extends Frame

{

    MenuBar menuBar;

    Dialog dialog;

    TextField textField;

    String str;



    DialogFrame(String title)

    {

        super(title);



        menuBar = new MenuBar();

        setMenuBar(menuBar);

        Menu menu = new Menu("Test");

        menuBar.add(menu);

        MenuItem item = new MenuItem("Dialog box");

        menu.add(item);



        str = "";

    }



    public void paint(Graphics g)

    {

        resize(300, 250);



        g.drawString("THE TEXT YOU ENTERED IS:", 70, 50);

        g.drawString(str, 70, 70);

    }



    public boolean action(Event evt, Object arg)

    {

        if (evt.target instanceof MenuItem)



 {

            if (arg == "Dialog box")

                ShowDialogBox();

        }

        else if (evt.target instanceof Button)

        {

            if (arg == "OK")

            {

                dialog.hide();

                str = textField.getText();

                repaint();

            }

        }



        return true;

    }



    protected void ShowDialogBox()

    {

        dialog = new Dialog(this, "Test Dialog", true);

        FlowLayout layout = new FlowLayout();

        dialog.setLayout(layout);



        textField = new TextField("", 20);

        Button button = new Button("OK");

        dialog.add(button);

        dialog.add(textField);



        dialog.show();

        dialog.resize(200, 100);

    }

}


Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the DialogApplet class from Java's Applet class.
Declare the frame-window and button objects.
Override the init() method.
Create the frame window.
Create and add the button component.
Override the action() method.
Determine whether the frame window is visible.
If the window is visible...
Hide the window.
Change the button's label to "Show Window."
Else if the window is hidden...
Show the window.
Set the window's size.
Change the button's label to "Hide Window."
Tell Java that the message was handled okay.
Define the frame window class.
Declare objects needed by the class.
Define the class's constructor.
Initialize the superclass (Frame).
Create the window's menu bar.
Initialize the display string.
Override the paint() method.
Resize the frame window.
Draw the display text in the window.
Override the action() method.
If the "Dialog Box" command was selected, create the dialog.
Else if the OK button was selected
Hide the dialog box.
Get the contents of the dialog's test field.
Tell Java to repaint the frame window.
Tell Java that the event was handled.
Define the ShowDialogBox() method.
Create the new dialog box and set its layout.
Create and add components to the dialog box.
Display and resize the dialog box.

NOTE
In addition to normal dialog boxes, Java supports file dialog boxes for loading and saving files. The file dialogs are represented by the FileDialog class. However, because Java applets have extremely limited access to files, file dialog boxes are not covered here.

Summary

You probably won't have much call for dialog boxes in your Java applets, but it's always good to know they're there when you need them. Using dialog boxes in conjunction with a frame window, you can inform the user of critical problems, as well as obtain information from the user without cluttering your main window with controls. Because dialog boxes are much like other display windows in Java, you can set up layout managers, add components, and control the dialog box using the many methods defined in the Dialog class or inherited from the class's superclasses.

Review Questions

  1. What are the three arguments accepted by the Dialog class's constructor?
  2. How do you display and hide a dialog box?
  3. Why are frame windows important to dialog boxes?
  4. What is the one control every dialog box should have?
  5. What's the difference between modal and modeless dialog boxes?
  6. How do you add components to the dialog box?

Review Exercises

  1. Write the code needed to create and display a dialog box with the title "Test Dialog" and with two button controls.
  2. Write an applet that can display a dialog box with a 2´2 grid containing four buttons.
  3. Modify DialogApplet so that the dialog box has both an OK and a Cancel button. If the user clicks the Cancel button, the dialog should be removed from the screen, but the string that was entered into the text field control should be ignored. Figure 24.2 shows the resultant applet, called DialogApplet2. (You can find the solution to this exercise in the CHAP24 folder of this book's CD-ROM.)

Figure 24.2 : This is the DialogApplet2 applet run-ning under Appletviewer.