1 package net.sf.openrocket.gui.adaptors;
3 import javax.swing.AbstractListModel;
4 import javax.swing.ComboBoxModel;
5 import javax.swing.event.ChangeEvent;
6 import javax.swing.event.ChangeListener;
8 import net.sf.openrocket.util.ChangeSource;
9 import net.sf.openrocket.util.Reflection;
12 public class EnumModel<T extends Enum<T>> extends AbstractListModel
13 implements ComboBoxModel, ChangeListener {
15 private final ChangeSource source;
16 private final String valueName;
17 private final String nullText;
19 private final Enum<T>[] values;
20 private Enum<T> currentValue = null;
22 private final Reflection.Method getMethod;
23 private final Reflection.Method setMethod;
27 public EnumModel(ChangeSource source, String valueName) {
28 this(source,valueName,null,null);
31 public EnumModel(ChangeSource source, String valueName, Enum<T>[] values) {
32 this(source, valueName, values, null);
35 @SuppressWarnings("unchecked")
36 public EnumModel(ChangeSource source, String valueName, Enum<T>[] values, String nullText) {
37 Class<? extends Enum<T>> enumClass;
39 this.valueName = valueName;
42 java.lang.reflect.Method getM = source.getClass().getMethod("get" + valueName);
43 enumClass = (Class<? extends Enum<T>>) getM.getReturnType();
44 if (!enumClass.isEnum()) {
45 throw new IllegalArgumentException("Return type of get" + valueName +
49 getMethod = new Reflection.Method(getM);
50 setMethod = new Reflection.Method(source.getClass().getMethod("set" + valueName,
52 } catch (NoSuchMethodException e) {
53 throw new IllegalArgumentException("get/is methods for enum '"+valueName+
54 "' not present in class "+source.getClass().getCanonicalName());
60 this.values = enumClass.getEnumConstants();
62 this.nullText = nullText;
64 stateChanged(null); // Update current value
65 source.addChangeListener(this);
71 public Object getSelectedItem() {
72 if (currentValue==null)
78 public void setSelectedItem(Object item) {
80 // Clear selection - huh?
83 if (item instanceof String) {
84 if (currentValue != null)
85 setMethod.invoke(source, (Object)null);
89 if (!(item instanceof Enum<?>)) {
90 throw new IllegalArgumentException("Not String or Enum, item="+item);
93 // Comparison with == ok, since both are enums
94 if (currentValue == item)
96 setMethod.invoke(source, item);
100 public Object getElementAt(int index) {
101 if (values[index] == null)
103 return values[index];
107 public int getSize() {
108 return values.length;
115 @SuppressWarnings("unchecked")
117 public void stateChanged(ChangeEvent e) {
118 Enum<T> value = (Enum<T>) getMethod.invoke(source);
119 if (value != currentValue) {
120 currentValue = value;
121 this.fireContentsChanged(this, 0, values.length);
128 public String toString() {
129 return "EnumModel["+source.getClass().getCanonicalName()+":"+valueName+"]";