Java Reference
In-Depth Information
Example 10•15: ItemChooser.java (continued)
Object[] values;
// Arbitrary values associated with each option
int selection;
// The selected choice
int presentation;
// How the choice is presented
// These are the legal values for the presentation field
public static final int LIST = 1;
public static final int COMBOBOX = 2;
public static final int RADIOBUTTONS = 3;
// These components are used for each of the 3 possible presentations
JList list;
// One type of presentation
JComboBox combobox;
// Another type of presentation
JRadioButton[] radiobuttons;
// Yet another type
// The list of objects that are interested in our state
ArrayList listeners = new ArrayList();
// The constructor method sets everything up
public ItemChooser(String name, String[] labels, Object[] values,
int defaultSelection, int presentation)
{
// Copy the constructor arguments to instance fields
this.name = name;
this.labels = labels;
this.values = values;
this.selection = defaultSelection;
this.presentation = presentation;
// If no values were supplied, use the labels
if (values == null) this.values = labels;
// Now create content and event handlers based on presentation type
switch(presentation) {
case LIST: initList(); break;
case COMBOBOX: initComboBox(); break;
case RADIOBUTTONS: initRadioButtons(); break;
}
}
// Initialization for JList presentation
void initList() {
list = new JList(labels); // Create the list
list.setSelectedIndex(selection); // Set initial state
// Handle state changes
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
ItemChooser.this.select(list.getSelectedIndex());
}
});
// Lay out list and name label vertically
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // vertical
this.add(new JLabel(name));
// Display choice name
this.add(new JScrollPane(list));
// Add the JList
}
// Initialization for JComboBox presentation
Search WWH ::




Custom Search