1 13 package org.eclipse.jface.internal.databinding.internal.swt; 14 15 import org.eclipse.core.databinding.observable.Diffs; 16 import org.eclipse.jface.internal.databinding.provisional.swt.AbstractSWTObservableValue; 17 import org.eclipse.jface.util.Assert; 18 import org.eclipse.swt.custom.CCombo; 19 import org.eclipse.swt.events.ModifyEvent; 20 import org.eclipse.swt.events.ModifyListener; 21 22 26 public class CComboObservableValue extends AbstractSWTObservableValue { 27 28 31 32 private final CCombo ccombo; 33 34 private final String attribute; 35 36 private boolean updating = false; 37 38 private String currentValue; 39 40 private ModifyListener modifyListener; 41 42 46 public CComboObservableValue(CCombo ccombo, String attribute) { 47 super(ccombo); 48 this.ccombo = ccombo; 49 this.attribute = attribute; 50 51 if (attribute.equals(SWTProperties.SELECTION) 52 || attribute.equals(SWTProperties.TEXT)) { 53 this.currentValue = ccombo.getText(); 54 modifyListener = new ModifyListener() { 55 56 public void modifyText(ModifyEvent e) { 57 if (!updating) { 58 String oldValue = currentValue; 59 currentValue = CComboObservableValue.this.ccombo 60 .getText(); 61 fireValueChange(Diffs.createValueDiff(oldValue, 62 currentValue)); 63 } 64 } 65 }; 66 ccombo.addModifyListener(modifyListener); 67 } else 68 throw new IllegalArgumentException (); 69 } 70 71 public void doSetValue(final Object value) { 72 String oldValue = ccombo.getText(); 73 try { 74 updating = true; 75 if (attribute.equals(SWTProperties.TEXT)) { 76 String stringValue = value != null ? value.toString() : ""; ccombo.setText(stringValue); 78 } else if (attribute.equals(SWTProperties.SELECTION)) { 79 String items[] = ccombo.getItems(); 80 int index = -1; 81 if (items != null && value != null) { 82 for (int i = 0; i < items.length; i++) { 83 if (value.equals(items[i])) { 84 index = i; 85 break; 86 } 87 } 88 if (index == -1) { 89 ccombo.setText((String ) value); 90 } else { 91 ccombo.select(index); } 93 } 94 } 95 } finally { 96 updating = false; 97 } 98 fireValueChange(Diffs.createValueDiff(oldValue, ccombo.getText())); 99 } 100 101 public Object doGetValue() { 102 if (attribute.equals(SWTProperties.TEXT)) 103 return ccombo.getText(); 104 105 Assert.isTrue(attribute.equals(SWTProperties.SELECTION), 106 "unexpected attribute: " + attribute); return ccombo.getText(); 110 } 111 112 public Object getValueType() { 113 Assert.isTrue(attribute.equals(SWTProperties.TEXT) 114 || attribute.equals(SWTProperties.SELECTION), 115 "unexpected attribute: " + attribute); return String .class; 117 } 118 119 122 public String getAttribute() { 123 return attribute; 124 } 125 126 131 public synchronized void dispose() { 132 super.dispose(); 133 134 if (modifyListener != null && !ccombo.isDisposed()) { 135 ccombo.removeModifyListener(modifyListener); 136 } 137 } 138 } 139 | Popular Tags |