Tutorial Tutorial Step 14

Building a Java text editor

Step 13: Hooking up event handling to the text area

Now let's hook up event handling to the JTextArea so your program will be setting the dirty flag whenever typing occurs. To do this, you need to add a Swing DocumentListener to the jTextArea's document (model) and check for insert, remove, and changed events.

  1. Switch to design mode and select jTextArea1.

  2. Click the document property in the left column of the Inspector, then right-click and choose Expose As Class Level Variable.

    A document1 object is placed in the Other folder of the component tree where you can now set its properties and events.

  3. Select document1 in the tree, then switch to the Events tab in the Inspector and create a changedUpdate() event. Notice that the following DocumentListener was added to the jbInit():
    document1.addDocumentListener(new TextEditFrame1_document1_documentAdapter(this));
  4. Insert the following code into the new void document1_changedUpdate(DocumentEvent e) event:
    dirty = true;
    
  5. Return to the designer, select document1, and create two more events from the Inspector for document1: insertUpdate() and removeUpdate(). Insert the same line of code in these events that you used in the changedUpdate() event.

    This will make sure that any character typed in the text area will force the dirty flag to true.

  6. Add the following three lines to the top of the okToAbandon() method so that now it will really be testing the dirty flag:
     if (!dirty) {
       return true;
     }
    
    The okToAbandon() method should now look like this:
    // Check if file is dirty.
    // If so get user to make a "Save? yes/no/cancel" decision.
    boolean okToAbandon() {
      if (!dirty) {
        return true;
      }
      int value =  JOptionPane.showConfirmDialog(this, "Save changes?",
                                           "Text Edit", JOptionPane.YES_NO_CANCEL_OPTION) ;
      switch (value) {
         case JOptionPane.YES_OPTION:
           // yes, please save changes
           return saveFile();
         case JOptionPane.NO_OPTION:
           // no, abandon edits
           // i.e. return true without saving
           return true;
         case JOptionPane.CANCEL_OPTION:
         default:
           // cancel
           return false;
      }
    }
    
  7. At this point, you should save your work, run the program, and test to see that dirty and clean states of the file work properly:

Tutorial Tutorial Step 14