26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

950 Files and Streams Chapter 16<br />

154 setVisible( true );<br />

155<br />

156 } // end TransactionProcessor construc<strong>to</strong>r<br />

157<br />

158 // enable user <strong>to</strong> select file <strong>to</strong> open<br />

159 private boolean openFile()<br />

160 {<br />

161 // display dialog so user can select file<br />

162 JFileChooser fileChooser = new JFileChooser();<br />

163 fileChooser.setFileSelectionMode(<br />

164 JFileChooser.FILES_ONLY );<br />

165<br />

166 int result = fileChooser.showOpenDialog( this );<br />

167<br />

168 // if user clicked Cancel but<strong>to</strong>n on dialog, return<br />

169 if ( result == JFileChooser.CANCEL_OPTION )<br />

170 return false;<br />

171<br />

172 // obtain selected file<br />

173 File fileName = fileChooser.getSelectedFile();<br />

174<br />

175 // display error if file name invalid<br />

176 if ( fileName == null ||<br />

177 fileName.getName().equals( "" ) ) {<br />

178 JOptionPane.showMessageDialog( this,<br />

179 "Invalid File Name", "Invalid File Name",<br />

180 JOptionPane.ERROR_MESSAGE );<br />

181<br />

182 return false;<br />

183 }<br />

184<br />

185 else {<br />

186<br />

187 // open file<br />

188 try {<br />

189 file = new RandomAccessFile( fileName, "rw" );<br />

190 openItem.setEnabled( false );<br />

191 newItem.setEnabled( true );<br />

192 updateItem.setEnabled( true );<br />

193 deleteItem.setEnabled( true );<br />

194 }<br />

195<br />

196 // process problems opening file<br />

197 catch ( IOException ioException ) {<br />

198 JOptionPane.showMessageDialog( this,<br />

199 "File does not exist", "Invalid File Name",<br />

200 JOptionPane.ERROR_MESSAGE );<br />

201<br />

202 return false;<br />

203 }<br />

204 }<br />

205<br />

206 return true; // file opened<br />

Fig. Fig. 16.20 16.20 16.20 Transaction-processing program (part 4 of 15).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!