Opening Files with JFileChooser

We conclude this chapter by introducing class JFileChooser. We use this class to display a dialog (known as the JFileChooser dialog) that enables users of our program to easily select files. To demonstrate the JFileChooser dialog, we enhance the example in Section 14.4, as shown in Fig. 14.37Fig. 14.38. The example now contains a graphical user interface, but still displays the same data as before. The constructor calls method analyzePath in line 34. This method then calls method getFile in line 68 to retrieve the File object.

Figure 14.37. Demonstrating JFileChooser.

(This item is displayed on pages 730 - 731 in the print version)

 1 // Fig. 14.37: FileDemonstration.java
 2 // Demonstrating the File class.
 3 import java.awt.BorderLayout;
 4 import java.awt.event.ActionEvent;
 5 import java.awt.event.ActionListener;
 6 import java.io.File;
 7 import javax.swing.JFileChooser;
 8 import javax.swing.JFrame;
 9 import javax.swing.JOptionPane;
10 import javax.swing.JScrollPane;
11 import javax.swing.JTextArea;
12 import javax.swing.JTextField;
13 
14 public class FileDemonstration extends JFrame
15 {
16 private JTextArea outputArea; // used for output
17 private JScrollPane scrollPane; // used to provide scrolling to output
18 
19 // set up GUI
20 public FileDemonstration()
21 {
22 super( "Testing class File" );
23 
24 outputArea = new JTextArea();
25 
26 // add outputArea to scrollPane
27 scrollPane = new JScrollPane( outputArea );
28 
29 add( scrollPane, BorderLayout.CENTER ); // add scrollPane to GUI
30 
31 setSize( 400, 400 ); // set GUI size
32 setVisible( true ); // display GUI
33 
34 analyzePath(); // create and analyze File object
35 } // end FileDemonstration constructor
36 
37 // allow user to specify file name
38 private File getFile()
39 {
40 // display file dialog, so user can choose file to open
41 JFileChooser fileChooser = new JFileChooser();
42 fileChooser.setFileSelectionMode( 
43  JFileChooser.FILES_AND_DIRECTORIES ); 
44 
45 int result = fileChooser.showOpenDialog( this );
46 
47 // if user clicked Cancel button on dialog, return
48 if ( result == JFileChooser.CANCEL_OPTION )
49 System.exit( 1 );
50 
51 File fileName = fileChooser.getSelectedFile(); // get selected file
52 
53 // display error if invalid
54 if ( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
55 {
56 JOptionPane.showMessageDialog( this, "Invalid File Name",
57 "Invalid File Name", JOptionPane.ERROR_MESSAGE );
58 System.exit( 1 );
59 } // end if
60 
61 return fileName;
62 } // end method getFile
63 
64 // display information about file user specifies
65 public void analyzePath()
66 {
67 // create File object based on user input
68 File name = getFile();
69 
70 if ( name.exists() ) // if name exists, output information about it
71 {
72 // display file (or directory) information
73 outputArea.setText( String.format(
74 "%s%s
%s
%s
%s
%s%s
%s%s
%s%s
%s%s
%s%s",
75 name.getName(), " exists",
76 ( name.isFile() ? "is a file" : "is not a file" ),
77 ( name.isDirectory() ? "is a directory" :
78 "is not a directory" ),
79 ( name.isAbsolute() ? "is absolute path" :
80 "is not absolute path" ), "Last modified: ",
81 name.lastModified(), "Length: ", name.length(),
82 "Path: ", name.getPath(), "Absolute path: ",
83 name.getAbsolutePath(), "Parent: ", name.getParent() ) );
84 
85 if ( name.isDirectory() ) // output directory listing
86 {
87 String directory[] = name.list();
88 outputArea.append( "

Directory contents:
" );
89 
90 for ( String directoryName : directory )
91 outputArea.append( directoryName + "
" );
92 } // end else
93 } // end outer if
94 else // not file or directory, output error message
95 {
96 JOptionPane.showMessageDialog( this, name +
97 " does not exist.", "ERROR", JOptionPane.ERROR_MESSAGE );
98 } // end else
99 } // end method analyzePath
100 } // end class FileDemonstration

Figure 14.38. Testing class FileDemonstration.

(This item is displayed on page 732 in the print version)

 1 // Fig. 14.38: FileDemonstrationTest.java
 2 // Testing the FileDmonstration class.
 3 import javax.swing.JFrame;
 4
 5 public class FileDemonstrationTest
 6 {
 7 public static void main( String args[] )
 8 {
 9 FileDemonstration application = new FileDemonstration();
10 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11 } // end main
12 } // end class FileDemonstrationTest
 

Method getFile is defined in lines 3862 of Fig. 14.37. Line 41 creates a JFileChooser and assigns its reference to fileChooser. Lines 4243 call method setFileSelectionMode to specify what the user can select from the fileChooser. For this program, we use JFileChooser static constant FILES_AND_DIRECTORIES to indicate that files and directories can be selected. Other static constants include FILES_ONLY and DIRECTORIES_ONLY.

Line 45 calls method showOpenDialog to display the JFileChooser dialog titled Open. Argument this specifies the JFileChooser dialog's parent window, which determines the position of the dialog on the screen. If null is passed, the dialog is displayed in the center of the screenotherwise, the dialog is centered over the application window (specified by the argument this). A JFileChooser dialog is a modal dialog that does not allow the user to interact with any other window in the program until the user closes the JFileChooser by clicking the Open or Cancel button. The user selects the drive, directory or file name, then clicks Open. Method showOpenDialog returns an integer specifying which button ( Open or Cancel) the user clicked to close the dialog. Line 48 tests whether the user clicked Cancel by comparing the result with static constant CANCEL_OPTION. If they are equal, the program terminates. Line 51 retrieves the file the user selected by calling JFileChooser method getSelectedFile. The program then displays information about the selected file or directory.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net