Java Utililty Methods JComboBox Selection

List of utility methods to do JComboBox Selection

Description

The list of methods to do JComboBox Selection are organized into topic(s).

Method

booleananySelected(JComboBox box)
Check if there are any selected items in the combobox.
if (box == null) {
    return false;
if (box.getModel().getSize() > 0) {
    return box.getSelectedItem() != null;
return false;
ObjectgetSelectedItem(Object combo)
get Selected Item
return ((JComboBox) combo).getSelectedItem();
StringgetSelectedName(JComboBox comboBox)
get Selected Name
return (String) comboBox.getSelectedItem();
StringgetSelectedString(JComboBox jcb)
get Selected String
return (jcb.getSelectedIndex() == -1) ? null : (String) jcb.getSelectedItem();
EgetTypedSelectedItemFromCombo(JComboBox combo)
Since JComboBox.getSelectedItem() returns a plain Object, this allows us to get the appropriate type of object instead.
int index = combo.getSelectedIndex();
return index != -1 ? combo.getItemAt(index) : null;
voidsafeSelectFirst(JComboBox cb)
safe Select First
if (cb.getModel().getSize() > 0) {
    cb.setSelectedIndex(0);
voidselectComboBoxItem(JComboBox jComboBox, String name)
select Combo Box Item
Optional itemToSelect = Optional.absent();
for (int i = 0; i < jComboBox.getItemCount(); i++) {
    final Object item = jComboBox.getItemAt(i);
    if (name.equals(item.toString())) {
        itemToSelect = Optional.of(item);
if (itemToSelect.isPresent())
...
voidselectStringInList(String string, JComboBox list)
Select an item in a JComboBox given an items string value
for (int i = 0; i < list.getModel().getSize(); i++) {
    if (String.valueOf(list.getModel().getElementAt(i)).equals(string)) {
        list.setSelectedIndex(i);
        return;
voidselectWithoutNotifyingListeners(JComboBox comboBox, int selectedIndex)
select Without Notifying Listeners
ItemListener[] il = comboBox.getItemListeners();
if (il != null) {
    for (ItemListener x : il)
        comboBox.removeItemListener(x);
comboBox.setSelectedIndex(selectedIndex);
if (il != null) {
    for (ItemListener x : il)
...
voidsetComboSelection(JComboBox cb, String sel)
set Combo Selection
ActionListener[] listeners = cb.getActionListeners();
for (int i = 0; i < listeners.length; i++)
    cb.removeActionListener(listeners[i]);
cb.setSelectedItem(sel);
for (int i = 0; i < listeners.length; i++)
    cb.addActionListener(listeners[i]);