1 package org.sapia.gumby.view.binding; 2 3 import java.util.ArrayList ; 4 import java.util.Collection ; 5 import java.util.Iterator ; 6 7 import javax.swing.JComboBox ; 8 9 import org.apache.commons.jxpath.JXPathContext; 10 import org.sapia.gumby.view.View; 11 12 27 public class ComboBinding extends AbstractJXPathBinding { 28 29 private Collection _options; 30 31 public void onBound(View owner, Object model) { 32 JComboBox list = (JComboBox ) acquireWidget(owner); 33 list.removeAllItems(); 34 initList(list, model); 35 } 36 37 public void onChanged(View owner, Object model) { 38 JComboBox list = (JComboBox ) acquireWidget(owner); 39 initList(list, model); 40 } 41 42 public void onUpdated(View owner, Object model) { 43 JComboBox list = (JComboBox ) acquireWidget(owner); 44 list.removeAllItems(); 45 initList(list, model); 46 } 47 48 public void updateModel(View owner, Object model) { 49 JXPathContext ctx = JXPathContext.newContext(model); 50 ctx.setLenient(true); 51 JComboBox list = (JComboBox ) acquireWidget(owner); 52 if(list.getSelectedIndex() >= 0) { 53 _expr.setValue(ctx, list.getSelectedItem()); 54 } 55 } 56 57 public void setOptions(Collection options) { 58 _options = options; 59 } 60 61 public void addOption(Object option) { 62 if(_options == null) { 63 _options = new ArrayList (); 64 } 65 _options.add(option); 66 } 67 68 private void initList(JComboBox comp, Object model) { 69 JXPathContext ctx = JXPathContext.newContext(model); 70 ctx.setLenient(true); 71 Object value = _expr.getValue(ctx); 72 if(value != null) { 73 if(_options != null) { 74 Iterator options = _options.iterator(); 75 int count = 0; 76 while(options.hasNext()) { 77 Object current = options.next(); 78 comp.addItem(value); 79 if(current.equals(value)) { 80 comp.setSelectedIndex(count); 81 } 82 count++; 83 } 84 } 85 } else { 86 Iterator options = _options.iterator(); 87 while(options.hasNext()) { 88 comp.addItem(options.next()); 89 } 90 } 91 } 92 } 93 | Popular Tags |