add method.
String[] dias = {"lunes", "martes", "miercoles"};
JComboBox dayChoice = new JComboBox(dias)
int index; String item; String obj; // obj can be any object type, but is commonly String JComboBox cb = new JComboBox(. . .);
| Result | Call | Description |
|---|---|---|
| cb.addActionListener(...); | Add listener -- same as for button. |
| Modifying a JComboBox | ||
| cb.setSelectedIndex(index); | Set default, visible, choice. |
| cb.setSelectedItem(obj); | Set default, visible, choice. |
| cb.add(item); | Add additional item to the list |
| cb.insert(item, index); | Add additional item after index. |
| cb.remove(item); | Remove item from the list |
| cb.remove(index); | Remove item as position index |
| Testing a JComboBox | ||
index = | cb.getSelectedIndex(); | Return index of selected item. |
obj = | cb.getSelectedItem(); | Return selected item. |
ActionEvent
is generated, and the listener's actionPerformed
method is called.
Use either getSelectedIndex to get the integer index of the
item that was selected, or getSelectedItem to get the
value (eg, a String) that was selected.
getSelectedItem method returns
an Object type, so it's necessary to downcast it back to
a String.
String[] fnt = {"Serif", "SansSerif", "Monospaced"};
JComboBox fontChoice = new JComboBox(fnt);
fontChoice.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox combo = (JComboBox)e.getSource();
currentFont = (String)combo.getSelectedItem();
}
}
);