1 7 8 package org.jdesktop.swing.data; 9 10 import java.beans.BeanInfo ; 11 import java.beans.Introspector ; 12 import java.beans.IntrospectionException ; 13 import java.beans.PropertyDescriptor ; 14 15 import java.lang.reflect.Method ; 16 17 31 public class JavaBeanDataModel extends DefaultDataModel { 32 33 private BeanInfo info; 34 private Class beanClass; 35 private Object bean; 37 public JavaBeanDataModel(Class beanClass) throws IntrospectionException { 38 this(beanClass, null); 39 } 40 41 48 public JavaBeanDataModel(Class beanClass, Object bean) throws IntrospectionException { 49 this.beanClass = beanClass; 50 this.bean = bean; 51 info = Introspector.getBeanInfo(beanClass); 52 53 PropertyDescriptor [] props = info.getPropertyDescriptors(); 55 for (int i = 0; i < props.length; i++) { 56 addField(new MetaData(props[i].getName(), 57 props[i].getPropertyType(), 58 props[i].getDisplayName())); 59 } 60 } 61 62 65 public void setJavaBean(Object bean) { 66 if (bean != null && bean.getClass() != beanClass) { 67 throw new RuntimeException ("ERROR: argument is not a " + 68 beanClass.toString()); 69 } 70 71 Object oldBean = this.bean; 72 this.bean = bean; 73 if (bean != oldBean) { 74 String [] fieldNames = getFieldNames(); 76 for (int i = 0; i < fieldNames.length; i++) { 77 fireValueChanged(fieldNames[i]); 78 } 79 } 80 } 81 82 85 public Object getJavaBean() { 86 return bean; 87 } 88 89 public Object getValue(String fieldName) { 90 if (getJavaBean() == null) { 91 return null; 92 } 93 PropertyDescriptor prop = getPropertyDescriptor(fieldName); 94 Method readMethod = prop.getReadMethod(); 95 if (readMethod != null) { 96 try { 97 return readMethod.invoke(getJavaBean(), new Object [0]); 98 } 99 catch (Exception ex) { 100 ex.printStackTrace(); 102 } 103 } 104 return null; 105 } 106 107 protected void setValueImpl(String fieldName, Object value) { 109 if (getJavaBean() == null) { 110 return; 111 } 112 PropertyDescriptor prop = getPropertyDescriptor(fieldName); 113 Method writeMethod = prop.getWriteMethod(); 114 if (writeMethod != null) { 115 try { 116 writeMethod.invoke(getJavaBean(), new Object [] {value}); 117 } 118 catch (Exception ex) { 119 ex.printStackTrace(); 121 } 122 } 123 } 124 125 private PropertyDescriptor getPropertyDescriptor(String name) { 126 PropertyDescriptor pd = null; 127 PropertyDescriptor [] desc = info.getPropertyDescriptors(); 128 for (int i = 0; i < desc.length; i++) { 129 if (name.equals(desc[i].getName())) { 130 pd = desc[i]; 131 break; 132 } 133 } 134 return pd; 135 } 136 } 137 | Popular Tags |