CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Layout

Controls and layout managers
Components
Combo boxes

A frame with a combo box

Common constructors of the JComboBox class

Constructor Description
JComboBox() Creates an empty combo box.
JComboBox(Object[]) Creates a combo box with the objects stored in the specified array.

Some methods that work with combo boxes

Method Description
getSelectedItem() Returns an Object type for the selected item.
getSelectedIndex() Returns an int value for the index of the selected item.
setSelectedIndex(intIndex) Selects the item at the specified index.
setEditable(boolean) If the boolean value is true, the combo box can be edited.
getItemCount() Returns the number of items stored in the combo box.
addItem(Object) Adds an item to the combo box.
removeItemAt(int) Removes the item at the specified index from the combo box.
removeItem(Object) Removes the specified item from the combo box.
addActionListener(ActionListener) Adds an action listener to the combo box.
addItemListener(ItemListener) Adds an item listener to the combo box.

Code that creates the combo box

private ArrayList<Product> products;
products = getProducts(); // returns an ArrayList of products
productComboBox = new JComboBox();
for (Product p : products)
    productComboBox.addItem(p.getDescription());
add(productComboBox);

Code that determines which item was selected

int i = productComboBox.getSelectedIndex();
Product p = products.get(i);
Previous | Summary | Text areas | Scroll panes | Check boxes | Radio buttons | Borders | Combo boxes | Event listeners | Lists | Multiple selections in a list | List models | Next