< Previous | Next >

Lesson 2.7: Program the Cancel button behavior

When using your application, you want to be able to easily back out of any changes that you start to make to an employees record if you decide not to submit the changes. In other words, you need to be able to cancel and clear the fields so you can start over. To add this functionality, you set some actionPerformed events on the Cancel button.

The following list describes the required behavior of the Cancel button:
  • If you click the Cancel button while in new mode, the application reverts out of new mode.
  • If you click the Cancel button while modifying an employee record, any values that you have changed revert back to the original values.

To add an actionPerformed event to the Cancel button to perform the required behavior:

  1. In the design view, right-click the Cancel button, and select Events > actionPerformed. The following code is generated in the getCancelButton() method:
    cancelButton.addActionListener(new java.awt.event.ActionListener() { 
       public void actionPerformed(java.awt.event.ActionEvent e) {    
          System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
       }
    });
  2. Replace the generated event stub with the following code:
    cancelButton.addActionListener(new java.awt.event.ActionListener() { 
       public void actionPerformed(java.awt.event.ActionEvent e) {    
          if (isNewMode) {
             getSwitchingDataObject().setSourceObject(getSelectedEmployeeRecord());
             isNewMode = false;
             updateMode();
          } else {
             getSelectedEmployeeRecord().refresh();
          }
       }
    });

Lesson checkpoint

In this lesson, you learned how to program the Cancel button with actionPerformed events.

< Previous | Next >