Java programming course: 16.9 Handling the Add button


Handling the Add button

All that remains now is to write some code for the Add button to enable the user to switch from "change" mode back into "add" mode. Go to the Design view of ZooKeeperPanel and double-click the Add button to generate its addButtonActionPerformed() method. All it needs to do is invoke clearZooKeeper() on the zooKeeperEditor instance:  

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
    zooKeeperEditor.clearZooKeeper();
}
 

After adding a new zookeeper it would be best to ensure nothing is selected in the list, since the form remains in "add" mode. Update the zooKeeperCreated() method in ZooKeeperList:

@Override
public void zooKeeperCreated(ZooKeeperEvent event) {
   model.loadModel();
   removeSelectionInterval(0, model.getSize());
}
 

You will have noticed that this is the same line of code that you previously added to zooKeeperRemoved(). Even though it is only a single line of code, given its slightly involved argument values there is a case for refactoring it into its own helper method. Define a new method in ZooKeeperList called deselectListItems():

void deselectListItems() {
    removeSelectionInterval(0, model.getSize());
}
 

Now you can modify the zooKeeperCreated() and zooKeeperRemoved() methods to invoke the new method:

@Override
public void zooKeeperCreated(ZooKeeperEvent event) {
    model.loadModel();
    deselectListItems();
}

@Override
public void zooKeeperRemoved(ZooKeeperEvent event) {
    model.loadModel();
    deselectListItems();
}
 

Returning to the addButtonActionPerformed() method in ZooKeeperPanel, that should also cause any selected item in the list to be de-selected, and this is now possible since you have created the deselectListItems() method:

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
    zooKeeperList.deselectListItems();
    zooKeeperEditor.clearZooKeeper();
}
 

That completes the coding for the zookeeper panels, and you should now be able to add, change and remove as many zookeepers as you wish. Bear in mind, however, that as it stands the data is only stored for as long as the application remains open. Saving the data to a disk file is covered in Section 19.



Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Monday, 27 October 2025

Captcha Image