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.events.ModifyEvent; 19 import org.eclipse.swt.events.ModifyListener; 20 import org.eclipse.swt.widgets.Combo; 21 22 26 public class ComboObservableValue extends AbstractSWTObservableValue { 27 28 private final Combo combo; 29 private final String attribute; 30 private boolean updating = false; 31 private String currentValue; 32 private ModifyListener modifyListener; 33 34 38 public ComboObservableValue(Combo combo, String attribute) { 39 super(combo); 40 this.combo = combo; 41 this.attribute = attribute; 42 43 if (attribute.equals(SWTProperties.SELECTION) 44 || attribute.equals(SWTProperties.TEXT)) { 45 this.currentValue = combo.getText(); 46 modifyListener = new ModifyListener() { 47 48 public void modifyText(ModifyEvent e) { 49 if (!updating) { 50 String oldValue = currentValue; 51 currentValue = ComboObservableValue.this.combo 52 .getText(); 53 fireValueChange(Diffs.createValueDiff(oldValue, 54 currentValue)); 55 } 56 } 57 }; 58 combo.addModifyListener(modifyListener); 59 } else 60 throw new IllegalArgumentException (); 61 } 62 63 public void doSetValue(final Object value) { 64 String oldValue = combo.getText(); 65 try { 66 updating = true; 67 if (attribute.equals(SWTProperties.TEXT)) { 68 String stringValue = value != null ? value.toString() : ""; combo.setText(stringValue); 70 } else if (attribute.equals(SWTProperties.SELECTION)) { 71 String items[] = combo.getItems(); 72 int index = -1; 73 if (items != null && value != null) { 74 for (int i = 0; i < items.length; i++) { 75 if (value.equals(items[i])) { 76 index = i; 77 break; 78 } 79 } 80 if (index == -1) { 81 combo.setText((String ) value); 82 } else { 83 combo.select(index); } 85 } 86 } 87 } finally { 88 updating = false; 89 } 90 fireValueChange(Diffs.createValueDiff(oldValue, combo.getText())); 91 } 92 93 public Object doGetValue() { 94 if (attribute.equals(SWTProperties.TEXT)) 95 return combo.getText(); 96 97 Assert.isTrue(attribute.equals(SWTProperties.SELECTION), 98 "unexpected attribute: " + attribute); return combo.getText(); 102 } 103 104 public Object getValueType() { 105 Assert.isTrue(attribute.equals(SWTProperties.TEXT) 106 || attribute.equals(SWTProperties.SELECTION), 107 "unexpected attribute: " + attribute); return String .class; 109 } 110 111 114 public String getAttribute() { 115 return attribute; 116 } 117 118 123 public synchronized void dispose() { 124 super.dispose(); 125 126 if (modifyListener != null && !combo.isDisposed()) { 127 combo.removeModifyListener(modifyListener); 128 } 129 } 130 } 131 | Popular Tags |