1 package org.sapia.gumby.view.binding; 2 3 import java.util.ArrayList ; 4 import java.util.Collection ; 5 import java.util.Iterator ; 6 import java.util.Vector ; 7 8 import javax.swing.JList ; 9 10 import org.apache.commons.jxpath.JXPathContext; 11 import org.sapia.gumby.view.View; 12 13 28 public class ListBinding extends AbstractJXPathBinding { 29 30 private Collection _options; 31 32 public void onBound(View owner, Object model) { 33 JList list = (JList ) acquireWidget(owner); 34 initList(list, model); 35 } 36 37 public void onChanged(View owner, Object model) { 38 onBound(owner, model); 39 } 40 41 public void onUpdated(View owner, Object model) { 42 onBound(owner, model); 43 } 44 45 public void updateModel(View owner, Object model) { 46 JXPathContext ctx = JXPathContext.newContext(model); 47 ctx.setLenient(false); 48 JList list = (JList ) acquireWidget(owner); 49 Collection newValues = new ArrayList (); 50 if(list.getSelectedIndex() >= 0) { 51 Object [] selected = list.getSelectedValues(); 52 for(int i = 0; i < selected.length; i++) { 53 newValues.add(selected[i]); 54 } 55 try { 56 _expr.setValue(ctx, newValues); 57 } catch(RuntimeException e) { 58 Collection currentValues = (Collection ) _expr.getValue(ctx); 59 if(currentValues != null) { 60 currentValues.clear(); 61 currentValues.addAll(newValues); 62 } 63 } 64 } 65 } 66 67 public void setOptions(Collection options) { 68 _options = options; 69 } 70 71 public void addOption(Object option) { 72 if(_options == null) { 73 _options = new ArrayList (); 74 } 75 _options.add(option); 76 } 77 78 private void initList(JList comp, Object model) { 79 JXPathContext ctx = JXPathContext.newContext(model); 80 ctx.setLenient(true); 81 Collection values = (Collection ) _expr.getValue(ctx); 82 Vector data = new Vector (); 83 if(values != null) { 84 if(_options != null) { 85 Iterator valuesItr = values.iterator(); 86 while(valuesItr.hasNext()) { 87 Object value = valuesItr.next(); 88 Iterator options = _options.iterator(); 89 int count = 0; 90 while(options.hasNext()) { 91 Object current = options.next(); 92 data.add(current); 93 if(current.equals(value)) { 94 comp.setSelectedIndex(count); 95 } 96 count++; 97 } 98 } 99 } 100 } else if(_options != null) { 101 Iterator options = _options.iterator(); 102 while(options.hasNext()) { 103 data.add(options.next()); 104 } 105 } 106 comp.setListData(data); 107 } 108 } 109 | Popular Tags |