Step 8: Add a Filer dialog and make it open a text file
Let's hook up the File|Open menu item to an event handler that presents the user with a Filer (file open dialog) for *.TXT files. If the user selects a file and clicks the OK button, then the event handler opens that text file and puts
the text into the TextArea.
- Select the Design tab on the AppBrowser, then select the Filer dialog from the Dialogs page of the Component Palette and click anywhere in the Component Tree or the UI Designer to place a Filer into your design.
- Select filer1 in the Other folder of the Component Tree and set its frame property to this in the Inspector.
- Select the File|Open menu item in the Component Tree (menuItem2), then click the Events tab in the Inspector.
- Double-click in its actionPerformed event to open that event handling method name for editing.
- Double-click, again, to create the event handler for File|Open, and locate the cursor inside it in the source code.
- Edit the event handling method source code to read as follows:
void menuItem2_actionPerformed(ActionEvent e) {
// Handle the File|Open menu item.
// Filer makes use of a java.awt.FileDialog, and so its
// mode property uses the same values as those of FileDialog.
filer1.setMode(FileDialog.LOAD); // Use the OPEN version of the dialog.
// Make the dialog visible as a modal (default) dialog box.
filer1.show();
// Upon return, getFile() will be null if user cancelled the dialog.
if (filer1.getFile() != null) {
// Non-null file property after return implies user
// selected a file to open.
// Display the name of the opened directory+file in the statusBar.
statusBar.setText("Opened " + filer1.getDirectory() + filer1.getFile());
// code will need to go here to actually load text
// from file into TextArea
}
}
Try running it and using the File|Open menu. Select some file and press OK. You should see the complete directory and filename displayed in the status line at the bottom of the window. However, no text appears in the text area. We'll take care of that in the next step.