Using dialog classes

Java's Swing library provides some pre-constructed classes for common kinds of user interactions. You can learn more about them on your own by looking at the on-line Java tutorial. The JFileChooser class was described on the back of the first page of the handout from class; a copy of that can be found here.

1. Prerequisites

A modal dialog is one that suspends other interactions until the user dismisses it. The dialog classes discussed here are all modal.

One requirement for using a modal dialog is that you must construct it with the window (JFrame) to which it is related—we call that window the dialog's parent. That means that you'll have to find some way to pass that. In the constructor for the Sprites class, there is already a local variable window of class SimWindow. You can get the JFrame you need by calling window.getWindow().

2. Displaying a message

The simplest predefined dialog class simply displays a message with a button for the user to press after reading it. The class JOptionPane provides a static method that will display such a message and wait for the user to press 'OK'. All you have to do is call

JOptionPane.showMessageDialog(parent, "message to display");

If you would like to be very slightly fancier, you can add two more parameters, as in

JOptionPane.showMessageDialog(parent, "message to display",
                                   "title string", messageKind);
The messageKind should be one of JOptionPane.ERROR_MESSAGE, JOptionPane.INFORMATION_MESSAGE, JOptionPane.WARNING_MESSAGE, or JOptionPane.PLAIN_MESSAGE.

3. The JFileChooser dialog

The familiar file-browser dialogs are provided by the class JFileChooser. Here are the methods you need to know:

4. Handing in the optional part

Hand in your source files for this part as assignment lab18b.
Cary Gray
Last modified: Tue Apr 24 07:42:28 CDT 2012