Java Reference
In-Depth Information
Example 10•15: ItemChooser.java (continued)
public int getPresentation() { return presentation; }
public String[] getLabels() { return labels; }
public Object[] getValues() { return values; }
/** Return the index of the selected item */
public int getSelectedIndex() { return selection; }
/** Return the object associated with the selected item */
public Object getSelectedValue() { return values[selection]; }
/**
* Set the selected item by specifying its index. Calling this
* method changes the on-screen display but does not generate events.
**/
public void setSelectedIndex(int selection) {
switch(presentation) {
case LIST: list.setSelectedIndex(selection); break;
case COMBOBOX: combobox.setSelectedIndex(selection); break;
case RADIOBUTTONS: radiobuttons[selection].setSelected(true); break;
}
this.selection = selection;
}
/**
* This internal method is called when the selection changes. It stores
* the new selected index, and fires events to any registered listeners.
* The event listeners registered on the JList, JComboBox, or JRadioButtons
* all call this method.
**/
protected void select(int selection) {
this.selection = selection; // Store the new selected index
if (!listeners.isEmpty()) { // If there are any listeners registered
// Create an event object to describe the selection
ItemChooser.Event e =
new ItemChooser.Event(this, selection, values[selection]);
// Loop through the listeners using an Iterator
for(Iterator i = listeners.iterator(); i.hasNext();) {
ItemChooser.Listener l = (ItemChooser.Listener)i.next();
l.itemChosen(e); // Notify each listener of the selection
}
}
}
// These methods are for event listener registration and deregistration
public void addItemChooserListener(ItemChooser.Listener l) {
listeners.add(l);
}
public void removeItemChooserListener(ItemChooser.Listener l) {
listeners.remove(l);
}
/**
* This inner class defines the event type generated by ItemChooser objects
* The inner class name is Event, so the full name is ItemChooser.Event
**/
public static class Event extends java.util.EventObject {
int selectedIndex;
// index of the selected item
Object selectedValue;
// the value associated with it
Search WWH ::




Custom Search