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 selectedObject. This will benullif nothing is selected so it is tested to ensure that it is notnullbefore continuing. Provided it is notnullthen it needs to be cast fromObjecttoZooKeeper - You then pass the
ZooKeeperobject to thesetZooKeeper()method ofZooKeeperEditor, 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.
Comments