Java Reference
In-Depth Information
Example 10•15: ItemChooser.java (continued)
void initComboBox() {
combobox = new JComboBox(labels);
// Create the combo box
combobox.setSelectedIndex(selection);
// Set initial state
// Handle changes to the state
combobox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
ItemChooser.this.select(combobox.getSelectedIndex());
}
});
// Lay out combo box and name label horizontally
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
this.add(new JLabel(name));
this.add(combobox);
}
// Initialization for JRadioButton presentation
void initRadioButtons() {
// Create an array of mutually exclusive radio buttons
radiobuttons = new JRadioButton[labels.length]; // the array
ButtonGroup radioButtonGroup = new ButtonGroup(); // used for exclusion
ChangeListener listener = new ChangeListener() { // A shared listener
public void stateChanged(ChangeEvent e) {
JRadioButton b = (JRadioButton)e.getSource();
if (b.isSelected()) {
// If we received this event because a button was
// selected, then loop through the list of buttons to
// figure out the index of the selected one.
for(int i = 0; i < radiobuttons.length; i++) {
if (radiobuttons[i] == b) {
ItemChooser.this.select(i);
return;
}
}
}
}
};
// Display the choice name in a border around the buttons
this.setBorder(new TitledBorder(new EtchedBorder(), name));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
// Create the buttons, add them to the button group, and specify
// the event listener for each one.
for(int i = 0; i < labels.length; i++) {
radiobuttons[i] = new JRadioButton(labels[i]);
if (i == selection) radiobuttons[i].setSelected(true);
radiobuttons[i].addChangeListener(listener);
radioButtonGroup.add(radiobuttons[i]);
this.add(radiobuttons[i]);
}
}
// These simple property accessor methods just return field values
// These are read-only properties. The values are set by the constructor
// and may not be changed.
public String getName() { return name; }
Search WWH ::




Custom Search