001 /* 002 * EnumerationValuePropertyEditor.java 003 * 004 * Created on March 28, 2006, 3:49 PM 005 * 006 * To change this template, choose Tools | Template Manager 007 * and open the template in the editor. 008 */ 009 010 package org.jdesktop.swingx.editors; 011 012 import java.beans.PropertyEditorSupport; 013 import java.util.HashMap; 014 import java.util.Map; 015 import org.jdesktop.swingx.EnumerationValue; 016 017 /** 018 * 019 * @author Richard 020 */ 021 public abstract class EnumerationValuePropertyEditor extends PropertyEditorSupport { 022 private String[] tags; 023 private Map<Object,EnumerationValue> values = new HashMap<Object,EnumerationValue>(); 024 private EnumerationValue defaultValue; 025 026 /** Creates a new instance of EnumerationValuePropertyEditor */ 027 public EnumerationValuePropertyEditor(EnumerationValue defaultEnum, EnumerationValue... enums) { 028 this.defaultValue = defaultEnum; 029 for (EnumerationValue v : enums) { 030 values.put(v.getValue(), v); 031 } 032 033 tags = new String[enums.length]; 034 int index = 0; 035 for (EnumerationValue v : enums) { 036 tags[index++] = v.getName(); 037 } 038 } 039 040 public String getJavaInitializationString() { 041 EnumerationValue value = values.get(getValue()); 042 if (value == null) { 043 return defaultValue == null ? "null" : defaultValue.getJavaInitializationString(); 044 } else { 045 return value.getJavaInitializationString(); 046 } 047 } 048 049 public String[] getTags() { 050 return tags; 051 } 052 053 public String getAsText() { 054 EnumerationValue value = values.get(getValue()); 055 if (value == null) { 056 return defaultValue == null ? null : defaultValue.getName(); 057 } else { 058 return value.getName(); 059 } 060 } 061 062 public void setAsText(String text) throws IllegalArgumentException { 063 EnumerationValue v = getValueByName(text); 064 if (v == null) { 065 //hmmmm, try again but trim text 066 if (text != null) { 067 v = getValueByName(text.trim()); 068 } 069 } 070 071 if (v == null) { 072 v = defaultValue; 073 } 074 075 setValue(v == null ? null : v.getValue()); 076 } 077 078 private EnumerationValue getValueByName(String name) { 079 for (EnumerationValue v : values.values()) { 080 String n = v == null ? null : v.getName(); 081 if (n == name || (n != null && n.equalsIgnoreCase(name))) { 082 return v; 083 } 084 } 085 return null; 086 } 087 }