Create JComboBox Model From Enum
4
I was looking for an easy way to populate a combo box with strings taken from an enumeration, and also to be able to pull out Enum objects from the combo box. After some searching, I found EnumComboBoxModel on the JDesktop website, but was not able to find any code.
Instead I came up with an easier solution that did not require me to define a new Model class, but instead uses javax.swing.DefaultComboBoxModel.
Sorry for the disorganization of the code, but hopefully you get the idea.
Instead I came up with an easier solution that did not require me to define a new Model class, but instead uses javax.swing.DefaultComboBoxModel.
Sorry for the disorganization of the code, but hopefully you get the idea.
/** Define enum class that will popuplate your combo box */
public enum E_ComboBoxEnum {
Item1("Item 1"),
Item2("Item 2"),
Item3("Item 3");
private final String _displayName;
/** constructor */
E_ComboBoxEnum(final String displayName) {
_displayName = displayName;
}
/** overrides method toString() in java.lang.Enum class */
public String toString(){
return _displayName;
}
} // end enum E_ComboBoxEnum
/** whatever class contains the JComboBox object, could be JFrame, JDialog, etc */
public class ComboBoxGUI extends javax.swing.JDialog {
private javax.swing.JComboBox _myComboBox;
public void createComboBox(){
_myComboBox = new javax.swing.JComboBox();
/** model is set to be a new instance of DefaultComboBoxModel. this model
is initialized with an array of all possible values of E_ExpirationDateIntervals */
_myComboBox.setModel(new javax.swing.DefaultComboBoxModel(E_ExpirationDateIntervals.values()));
}
/** the combo box will now display the Strings defined in the E_ComboBoxEnum class, in the order that they were defined. */
/** _myComboBox.getSelectedItem() will return an E_ComboBoxEnum object (well technically a generic object that can be cast into an E_ComboBoxEnum object) */
} // end class ComboBoxGUI






There are currently no comments for this snippet.