1 package net.sf.openrocket.gui.adaptors;
3 import java.util.EventObject;
5 import javax.swing.AbstractListModel;
6 import javax.swing.ComboBoxModel;
8 import net.sf.openrocket.util.ChangeSource;
9 import net.sf.openrocket.util.Reflection;
10 import net.sf.openrocket.util.StateChangeListener;
13 public class EnumModel<T extends Enum<T>> extends AbstractListModel
14 implements ComboBoxModel, StateChangeListener {
16 private final ChangeSource source;
17 private final String valueName;
18 private final String nullText;
20 private final Enum<T>[] values;
21 private Enum<T> currentValue = null;
23 private final Reflection.Method getMethod;
24 private final Reflection.Method setMethod;
28 public EnumModel(ChangeSource source, String valueName) {
29 this(source,valueName,null,null);
32 public EnumModel(ChangeSource source, String valueName, Enum<T>[] values) {
33 this(source, valueName, values, null);
36 @SuppressWarnings("unchecked")
37 public EnumModel(ChangeSource source, String valueName, Enum<T>[] values, String nullText) {
38 Class<? extends Enum<T>> enumClass;
40 this.valueName = valueName;
43 java.lang.reflect.Method getM = source.getClass().getMethod("get" + valueName);
44 enumClass = (Class<? extends Enum<T>>) getM.getReturnType();
45 if (!enumClass.isEnum()) {
46 throw new IllegalArgumentException("Return type of get" + valueName +
50 getMethod = new Reflection.Method(getM);
51 setMethod = new Reflection.Method(source.getClass().getMethod("set" + valueName,
53 } catch (NoSuchMethodException e) {
54 throw new IllegalArgumentException("get/is methods for enum '"+valueName+
55 "' not present in class "+source.getClass().getCanonicalName());
61 this.values = enumClass.getEnumConstants();
63 this.nullText = nullText;
65 stateChanged(null); // Update current value
66 source.addChangeListener(this);
72 public Object getSelectedItem() {
73 if (currentValue==null)
79 public void setSelectedItem(Object item) {
81 // Clear selection - huh?
84 if (item instanceof String) {
85 if (currentValue != null)
86 setMethod.invoke(source, (Object)null);
90 if (!(item instanceof Enum<?>)) {
91 throw new IllegalArgumentException("Not String or Enum, item="+item);
94 // Comparison with == ok, since both are enums
95 if (currentValue == item)
97 setMethod.invoke(source, item);
101 public Object getElementAt(int index) {
102 if (values[index] == null)
104 return values[index];
108 public int getSize() {
109 return values.length;
116 @SuppressWarnings("unchecked")
118 public void stateChanged(EventObject e) {
119 Enum<T> value = (Enum<T>) getMethod.invoke(source);
120 if (value != currentValue) {
121 currentValue = value;
122 this.fireContentsChanged(this, 0, values.length);
129 public String toString() {
130 return "EnumModel["+source.getClass().getCanonicalName()+":"+valueName+"]";