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.
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()
.
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
TheJOptionPane.showMessageDialog(parent, "message to display", "title string", messageKind);
messageKind
should be one of
JOptionPane.ERROR_MESSAGE
,
JOptionPane.INFORMATION_MESSAGE
,
JOptionPane.WARNING_MESSAGE
, or
JOptionPane.PLAIN_MESSAGE
.
JFileChooser
dialogThe familiar file-browser dialogs are provided by the class
JFileChooser
.
Here are the methods you need to know:
JFileChooser()
Construct a chooser. You will specify the parent window when you show the dialog with one of the next two methods.
int showOpenDialog(JFrame parent)
int showSaveDialog(JFrame parent)
These two instance methods show the dialog to select a file for
reading or for writing, respectively. If the user hits the
button indicating they want the action, the calue returned will be
JFileChooser.APPROVE_OPTION
; any other return value
indicates that no action should be taken.
File getSelectedFile()
This returns the name of the selected file, but it does so as the
type java.io.File
, which you will need to import.
You can pass the File
value to a constructor for either
PrintWriter
or FileInputStream
. If you
want to get the name of the File
as a string, call its
getName()
method.
lab18b
.