Java Reference
In-Depth Information
These variables are not yet instantiated using new ; this will happen in method
openFile which is described below. We then add the code for the dialogue at the
position marked ' //Code for opening a file has to go here. 'inclass Edi-
torSkeletonFrame . The code for the resulting method openFile is listed below.
The complete listing for the class EditorFrame can be downloaded from the topic's
home page.
1. public void openFile(){
2.
if (chooser == null ){
3.
chooser = new JFileChooser(startPath);
4.
}
5.
int returnVal = chooser.showOpenDialog( this );
6.
if (returnVal == JFileChooser.APPROVE_OPTION)
7.
{
8.
File selectedFile = chooser.getSelectedFile();
9.
try {
10.
FileReader reader = new FileReader(selectedFile);
11.
textDisplayPane.read(reader, null );
12.
reader.close();
13.
} catch (IOException e){
14.
System.out.println("Problems opening or reading "
15.
+selectedFile.getName());
16.
}
17.
}// if
18. }
The first lines create a file selection dialogue if this has not been done before. This
is because we would like to avoid unnecessarily creating new instances of it. The
condition in the if -statement in Line 2 is true only at its first execution. Then
an instance of the file chooser is created and assigned to the variable chooser in
Line 3. From that point on chooser is not null and hence the statement in Line 3
is not executed again.
We then make the file chooser visible in Line 5 as an 'Open'-dialogue using
method showOpenDialog(this) . The dialogue is modal and thus blocks its par-
ent component as long as it is visible. In our case the parent component is the
EditorFrame which is passed to the dialogue as this . The execution of the code
of the EditorFrame is stopped at Line 5 until either the 'Open' or the 'Cancel'
button of the dialogue is selected. Then the variable returnVal receives the value
APPROVE_OPTION or CANCEL_OPTION respectively, the dialogue is made invisible
and the execution of the code of EditorFrame is continued.
If APPROVE_OPTION is selected we find out which file has been selected using
method getSelectedFile . Then a file reader for this file is created in Line 10.
This reader is passed to the read method of JTextPanel which loads the file and
displays the text. As explained in Section 10.1, readers have to be placed inside a
try-catch block. This concludes the implementation of the file opening procedure
of our editor.
Search WWH ::




Custom Search