Tutorial Tutorial Step 15

Step 14: Show filename and state in the window caption

In this step, we will add code that uses the caption of the application to display the current filename and to display an asterisk if the file is "dirty". To do this, we'll create a new method that will update the caption, then call it from places where the code changes either the current file name or the dirty flag. We'll name this new method updateCaption().

  1. Add this method just above the fileExit_actionPerformed() method in the source code. To get there quickly, click on the fileExit_actionPerformed(ActionEvent) method in the structure pane. This will move the cursor to that event handling method and highlight it in the Source Pane. Click in the source pane to place the cursor just above this method.

    Insert the following new method there:

    /**
     * Update the caption of the application to show the filename and its dirty state.
     */
    void updateCaption() {
      String caption;
    
      if (currFileName == null) {
         // synthesize the "Untitled" name if no name yet.
         caption = "Untitled";
      }
      else {
        caption = currFileName;
      }
    
      // add a "*" in the caption if the file is dirty.
      if (dirty) {
        caption = "* " + caption;
      }
      caption = "TextEdit - " + caption;
      this.setTitle(caption);
    }
    
  2. Now call updateCaption() from each of the places the dirty flag actually changes, or whenever you change the currFileName.

    Specifically, put the call updateCaption(); in the following places:

  3. Run your application and watch the caption as you perform the following operations:

Tutorial Tutorial Step 15