Using enums in list models

As most (Java) programmers realized, the “int enum pattern” is fought with several deficiencies. With the release of Java 1.5, enums became a integral part of the Java programming language, and their use is wide spread these days–which surely is a good thing on its own.

But when it comes to GUI creation, there is one problem that is not addressed by the standard Java libraries (at least in the current release, which is 1.6): There is no easy way to use an enum in a JComboBox and the like.

There is a clean way to use Java enums in as list models:

import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;

/**
 * Allows to use an enum in a combo box.
 *
 * @param  the enum class this combo box model should represent.
 * @author Matthias Treydte <waldheinz at gmail.com>
 */
public class EnumComboBoxModel>
        extends AbstractListModel
        implements ComboBoxModel {

    private static final long serialVersionUID = 6121625045237370061L;
    private final Class enumClass;
    private int selectedIndex;

    public EnumComboBoxModel(Class clazz) {
        this.enumClass  = clazz;
        this.selectedIndex = 0;
    }

    public int getSize() {
        return enumClass.getEnumConstants().length;
    }

    public Object getElementAt(int index) {
        return enumClass.getEnumConstants()[index];
    }

    public void setSelectedItem(Object item) {
        if (item != null) {
            for (int i=0; i < getSize(); i++) {
                if (getElementAt(i) == item) {
                    selectedIndex = i;
                    return;
                }
            }
        }
        selectedIndex = -1;
    }

    public Object getSelectedItem() {
        if (selectedIndex == -1) return null;
        return enumClass.getEnumConstants()[selectedIndex];
    }
}

About this entry