Implementing a Modal Dialog Box

In the MyNotepad application, when a user clicks New on the File menu, the code in this event handler determines if there is text in the edit control. If so, it opens a modal dialog box that displays a message asking the user if they want to save the text. If the user clicks the Yes button, the MyNotepad.FileMenuSaveAs_click method is called, which allows the user to choose a file and save the current text. If the user clicks No, the edit control is cleared, and the title displayed on the main form becomes “Untitled – MyNotepad”.

In the FileMenuNew_click method, the invocation of this dialog box and retrieval of the dialog result is done in one line as follows:

         int result = new NewDialog().showDialog(this);     

While the modal dialog box is open, the dialog result value can be set from within the dialog form. The DialogResult class contains integer constants used for this purpose, but any integer can be returned. The button's dialogResult properties were used in this case, which accomplishes the same purpose of setting the DialogResult value.

As an example, clicking the yesButton control sets DialogResult.Yes. This result is then returned from the showDialog method in the owner class when the dialog box is closed. The integer result returned by showDialog is then used to determine what action to take.

The NewDialog.java form was created as a new form using the same Form template used by the main application form. Note the main() method is not required for modal dialog boxes and was removed from this example (leaving it in does not cause errors, but is not considered good practice). Also, extraneous template comments for this method were removed.

Using a Message Box as a Modal Dialog Box

You can also use a message box instead of a custom modal dialog box for simple cases. The click event handler for the About MyNotepad menu item on the Help menu uses a MessageBox object as follows:

    private void HelpMenuAbout_click(Object sender, Event e)

    {

      MessageBox.show("Version: Visual J++ 6.0", "MyNotepad");

    }