Saturday, February 10, 2007

How can I create a modal dialog box?

Modal dialog boxes are extremely useful for display alert messages, and for capturing the user's attention. You can create a simple modal dialog box, and then it will remain visible and will maintain focus until it is hidden (usually when the user clicks on a button). Here's a simple example.

import java.awt.*;
import java.awt.event.*;

public class DialogExample {
private static Dialog d;

public static void main(String args[])
{
Frame window = new Frame();

// Create a modal dialog
d = new Dialog(window, "Alert", true);

// Use a flow layout
d.setLayout( new FlowLayout() );

// Create an OK button
Button ok = new Button ("OK");
ok.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
// Hide dialog
DialogExample.d.setVisible(false);
}
});

d.add( new Label ("Click OK to continue"));
d.add( ok );

// Show dialog
d.pack();
d.setVisible(true);
System.exit(0);
}
}

The most important part of the program is the line that initializes the dialog. Notice the parameters we pass to it. The first parameter is a parameter for a window, and the second the title for the dialog. The final parameter controls whether the dialog is modal or not (true modal, false non-modal).

d = new Dialog(window, "Alert", true);
Using dialogs is easy, and can communicate information to users effectively. For those wishing to use the example, remember that it requires JDK1.1 or higher.


SOURCE : www.referjava.com

No comments: