1 7 8 package org.jdesktop.swing.binding; 9 10 import java.beans.PropertyChangeEvent ; 11 import java.beans.PropertyChangeListener ; 12 import java.util.ArrayList ; 13 import java.util.List ; 14 15 import javax.swing.AbstractListModel ; 16 import javax.swing.DefaultListModel ; 17 import javax.swing.JComponent ; 18 import javax.swing.JList ; 19 import javax.swing.ListModel ; 20 21 import org.jdesktop.swing.data.DataConstants; 22 import org.jdesktop.swing.data.DataModel; 23 import org.jdesktop.swing.data.MetaData; 24 import org.jdesktop.swing.data.SelectionModel; 25 26 public class ListBinding extends AbstractBinding { 27 28 private JList list; 29 30 public ListBinding(JList list, DataModel model, String fieldName) { 31 super(list, model, fieldName, AbstractBinding.AUTO_VALIDATE_NONE); 32 } 33 34 35 public boolean isModified() { 36 return false; 37 } 38 39 public boolean isValid() { 40 return true; 41 } 42 43 public JComponent getComponent() { 44 return list; 45 } 46 47 protected void setComponent(JComponent component) { 48 list = (JList )component; 49 configureSelection(); 50 } 51 52 private void configureSelection() { 53 Object selectionMeta = metaData.getCustomProperty(DataConstants.SELECTION_MODEL); 54 if (selectionMeta instanceof SelectionModel) { 55 new ListSelectionBinding((SelectionModel) selectionMeta, list.getSelectionModel()); 56 } 57 58 } 59 60 61 protected void installMetaDataListener() { 62 PropertyChangeListener l = new PropertyChangeListener () { 63 64 public void propertyChange(PropertyChangeEvent evt) { 65 if (DataConstants.SELECTION_MODEL.equals(evt.getPropertyName())) { 66 configureSelection(); 67 } 68 69 } 70 71 }; 72 metaData.addPropertyChangeListener(l); 73 } 74 75 76 protected Object getComponentValue(){ 77 ListModel model = list.getModel(); 78 Class klazz = metaData.getElementClass(); 79 80 if (klazz.equals(List .class)) { 81 List lvalue = new ArrayList (); 82 for (int i = 0, size = model.getSize(); i < size; i++) { 83 lvalue.add(model.getElementAt(i)); 84 } 85 return lvalue; 86 } 87 else if (klazz.isArray()) { 88 89 int size = model.getSize(); 91 Object [] values = new Object [size]; 92 for (int i = 0; i < size; i++) { 93 values[i] = model.getElementAt(i); 94 } 95 return values; 96 } 97 return null; 98 } 99 100 protected void setComponentValue(Object value) { 101 Class klazz = metaData.getElementClass(); 102 if (klazz.equals(List .class)) { 103 List lvalue = (List )value; 104 if (lvalue != null) { 105 list.setListData(lvalue.toArray()); 106 } 107 } 108 else if (klazz.isArray()) { 109 Object [] arrayValue = (Object [])value; 110 111 if (arrayValue != null) { 112 list.setListData(arrayValue); 113 } else { 114 list.setModel(new DefaultListModel ()); 116 } 117 } 118 } 119 } 120 121 | Popular Tags |