textArea1.setText("");
.
// clear the current filename and set the file as clean: currFileName = null; dirty = false;
/** * Check if file is dirty. * If so get user to make a "Save? yes/no/cancel" decision. * @return true if user saved here (Yes), or didn't care (No) * @return false if user hits cancel. */ boolean okToAbandon() { message1.setButtonSet(Message.YES_NO_CANCEL); message1.setTitle("Text Edit"); message1.setMessage("Save changes?"); message1.show(); switch (message1.getResult()) { case Message.YES: // Yes, please save changes. return saveFile(); case Message.NO: // No, abandon edits. // i.e. return true without saving return true; case Message.CANCEL: default: // Cancel. return false; } }The above method, which we will be finishing in a later step, will be called whenever the user chooses File|New, File|Open, or File|Exit. Its purpose is to test to see if the text needs to be saved (is "dirty"). If it is dirty, this method uses a "Yes, No, Cancel" Message dialog for asking the user whether to save. This method also calls saveFile() if the user clicks the Yes button. When the method returns, the boolean return value, if true, indicates it is ok to abandon this file because it was clean or the user clicked the Yes or No button, and if false, means the user clicked cancel. The code that will actually check to see if the file is dirty will be added in a later step. For now, this method always treats the file as dirty, even if no change has been made to the text. Later you will add a method to set the dirty variable to true when the user types in the text area, and you will add code to the top of okToAbandon() to test the dirty variable.
The following are the modified event handlers:
void menuItem1_actionPerformed(ActionEvent e) { // Handle the File|New menu item. if (okToAbandon()) { // Clear the text of the TextArea. textArea1.setText(""); // Clear the current filename and set the file as clean. currFileName = null; dirty = false; } }
void menuItem2_actionPerformed(ActionEvent e) { // Handle the File|Open menu item. if (!okToAbandon()) { return; } // 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 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. // Call openFile to attempt to load the text from file into TextArea. openFile(filer1.getDirectory()+filer1.getFile()); } }
//File | Exit action performed. public void fileExit_actionPerformed(ActionEvent e) { if (okToAbandon()) { System.exit(0); } }
Each of these menu event handling methods now only does its task if okToAbandon() returns true.