File I/O with GUIs
Since the majority of applications nowadays have GUI interfaces, it would be nice
to provide such an interface for our fi le handling programs. The reader will almost
certainly have used fi le handling applications that provide such an interface. A par-
ticularly common feature of such applications is the provision of a dialogue box that
allows the user to navigate the computer's fi le system and select either an existing
fi le for opening or the destination directory for a fi le that is to be created. By employ-
ing Swing class JFileChooser , we can display a dialogue box that will allow the
user to do just that.
A JFileChooser object opens a modal dialogue box ['Modal' means that the
window must be dismissed before further processing may be carried out] that dis-
plays the system's directory structure and allows the user to traverse it. Once a
JFileChooser object has been created, method setFileSelectionMode may be used to
specify whether fi les and/or directories are selectable by the user, via the following
JFileChooser fi leChooser = new JFileChooser();
We can then call either showOpenDialog or showSaveDialog . The former dis-
plays a dialogue box with 'Open' and 'Cancel' buttons, while the latter displays a
dialogue box with 'Save' and 'Cancel' buttons. Each of these methods takes a single
argument and returns an integer result. The argument specifi es the JFileChooser 's
parent component, i.e. the window over which the dialogue box will be displayed.
The above will cause the dialogue box to be displayed in the centre of the appli-
cation window. If null is passed as an argument, then the dialogue box appears in the
centre of the screen.
The integer value returned may be compared with either of the following inbuilt
Testing against the latter of these constants will return 'true' if the user has
selected a fi le.