Using a JFileChooser to allow a user to select a file |
In the link finder example from last class the program decided what file to read and what file to write by having the filenames as part of the Java code. Most applications that use files ask the user what files to read or write by displaying a file dialog. We can do that in Java using a specialized GUI component called a JFileChooser.
Here is code that allows a user to select a file to read from:
JFileChooser dialog = new JFileChooser(); // Display the dialog box and make sure the user did not cancel. if (dialog.showOpenDialog(text) == JFileChooser.APPROVE_OPTION) { // Find out which file the user selected. file = dialog.getSelectedFile(); // Code to process the file is omitted. }Selecting a file for writing is similar except you call showSaveDialog instead of showOpenDialog.
See TextEditor for an example of a complete program using these dialogs.
Using a JFileChooser to allow a user to select a file |