Java Reference
In-Depth Information
F
IGURE
14.10
JFileChooser
can be used to display a file dialog for opening a file.
Listing 14.16 gives a program that prompts the user to choose a file and displays its con-
tents on the console.
L
ISTING
14.16
ReadFileUsingJFileChooser.java
1
import
java.util.Scanner;
2
import
javax.swing.JFileChooser;
3
4
public class
ReadFileUsingJFileChooser {
5
public static void
main(String[] args)
throws
Exception {
6
7
if
(
8 ==
JFileChooser fileChooser =
new
JFileChooser();
create a
JFileChooser
display file chooser
check status
fileChooser.showOpenDialog(
null
)
JFileChooser.APPROVE_OPTION
) {
9
// Get the selected file
10 java.io.File file =
fileChooser.getSelectedFile()
;
getSelectedFile
11
12
// Create a Scanner for the file
13 Scanner input =
new
Scanner(file);
14
15
// Read text from the file
16
while
(input.hasNext()) {
17 System.out.println(input.nextLine());
18 }
19
20
// Close the file
21 input.close();
22 }
23
else
{
24 System.out.println(
"No file selected"
);
25 }
26 }
27 }
The program creates a
JFileChooser
in line 6. The
showOpenDialog(null)
method dis-
plays a dialog box, as shown in Figure 14.10. The method returns an
int
value, either
APPROVE_OPTION
or
CANCEL_OPTION
, which indicates whether the
Open
button or the
Cancel
button was clicked.
The
getSelectedFile()
method (line 10) returns the selected file from the file dialog
box. Line 13 creates a scanner for the file. The program continuously reads the lines from the
file and displays them to the console (lines 16-18).
showOpenDialog
APPROVE_OPTION
getSelectedFile
✓
✓
Check
14.36
Point
How do you create a File Open dialog box? What is returned from invoking
getSelectFile()
on a
JFileChooser
object?