Java Reference
In-Depth Information
48 tests whether the user clicked
Cancel
by comparing the result with
static
constant
CANCEL_OPTION
. If they're equal, the program terminates. Line 84 calls
JFileChooser
method
getSelectedFile
to retrieve a
File
object (package
java.io
) representing the file
or directory that the user selected, then calls
File
method
toPath
to return a
Path
object.
The program then displays information about the selected file or directory.
1
// Fig. 15.12: JFileChooserDemo.java
2
// Demonstrating JFileChooser.
3
import
java.io.IOException;
4
import
java.nio.file.DirectoryStream;
5
import
java.nio.file.Files;
6
import
java.nio.file.Path;
7
import
java.nio.file.Paths;
8
9
import
javax.swing.JFileChooser;
import
javax.swing.JFrame;
10
import
javax.swing.JOptionPane;
11
import
javax.swing.JScrollPane;
12
import
javax.swing.JTextArea;
13
14
public class
JFileChooserDemo
extends
JFrame
15
{
16
private final
JTextArea outputArea;
// displays file contents
17
18
// set up GUI
19
public
JFileChooserDemo()
throws
IOException
20
{
21
super
(
"JFileChooser Demo"
);
22
outputArea =
new
JTextArea();
23
add(
new
JScrollPane(outputArea));
// outputArea is scrollable
24
analyzePath();
// get Path from user and display info
25
}
26
27
// display information about file or directory user specifies
28
public void
analyzePath()
throws
IOException
29
{
30
// get Path to user-selected file or directory
31
Path path = getFileOrDirectoryPath();
32
33
if
(path !=
null
&& Files.exists(path))
// if exists, display info
34
{
35
// gather file (or directory) information
36
StringBuilder builder =
new
StringBuilder();
37
builder.append(String.format(
"%s:%n"
, path.getFileName()));
38
builder.append(String.format(
"%s a directory%n"
,
39
Files.isDirectory(path) ?
"Is"
:
"Is not"
));
40
builder.append(String.format(
"%s an absolute path%n"
,
41
path.isAbsolute() ?
"Is"
:
"Is not"
));
42
builder.append(String.format(
"Last modified: %s%n"
,
43
Files.getLastModifiedTime(path)));
44
builder.append(String.format(
"Size: %s%n"
, Files.size(path)));
45
builder.append(String.format(
"Path: %s%n"
, path));
Fig. 15.12
|
Demonstrating
JFileChooser
. (Part 1 of 2.)