Java programming course: 16.7 Modifying existing zookeeper details


Modifying existing zookeeper details

Now that you have completed the code necessary to add new zookeepers you need to enable their details to be changed. What you will do is detect whenever the user selects one of the names in ZooKeeperList and pass that selected ZooKeeper object to ZooKeeperEditor so that it transitions into "change" mode.

The JList class (of which ZooKeeperList is a subclass) supports the fact that client objects may wish to listen to selections in the list. All client objects need to do is implement the ListSelectionListener interface and provide the appropriate code in its required valueChanged() method. Then you can pass the client object as an argument to the addListSelectionListener() method of JList. You will now code these steps.

Firstly, change the class header of ZooKeeperPanel to implement ListSelectionListener (you will also need to import the javax.swing.event package):

package virtualzoo.ui;

import virtualzoo.core.*;
import javax.swing.event.*;

public class ZooKeeperPanel extends javax.swing.JPanel implements ListSelectionListener {
 

Now you need to code the only method required by the interface:

@Override
public void valueChanged(ListSelectionEvent e) {
    // A zoo keeper has been selected from ZooKeeperList
    Object selected = zooKeeperList.getSelectedValue();
    if (selected != null) {
        ZooKeeper zooKeeper = (ZooKeeper) selected;
        zooKeeperEditor.setZooKeeper(zooKeeper);
    }
}
 
  • The valueChanged() method will be called every time the user selects a zookeeper from the list
  • The getSelectedValue() method retrieves the selected Object. This will be null if nothing is selected so it is tested to ensure that it is not null before continuing. Provided it is not null then it needs to be cast from Object to ZooKeeper
  • You then pass the ZooKeeper object to the setZooKeeper() method of ZooKeeperEditor, which you coded earlier

You need to ensure you listen to the list events so invoke the registration in the constructor:

public ZooKeeperPanel() {
    initComponents();
    admin = ZooAdministrator.getInstance();
    admin.addZooKeeperListener(zooKeeperList);
    zooKeeperList.addListSelectionListener(this);
}
 

Run the application and enter two or three new zookeepers. Now, select one of the names from the list and notice that the editor displays the selected one's details in "change" mode. You can edit the details and click Save, and if you modified the name, you should see this reflected in the list on the left.



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
Saturday, 13 December 2025

Captcha Image