Search code examples
javadata-bindingjface

JFace Databinding using a Comboviewer


I want to use JFace Databinding for a ComboViewer but I can't figure out how to do this correctly.

That's my current progress:

    CCombo c= new CCombo(grpCpu, SWT.BORDER);
    c.setEditable(false);

    ComboViewer c_viewer = new ComboViewer(text_6);
    c_viewer.setContentProvider(new ArrayContentProvider());
    c_viewer.setLabelProvider(new LabelProvider() {

        @Override
        public String getText(Object element) {
            return Activator.getSomeService().key2Value((Integer) element);
        }

    });
    c.setInput(new int[]{1, 2, 3});

The key2Value method (simple map to convert int values to strings):

public String key2Value(int key){
    return someHashMap.get(key);
}

And the Databinding:

// IObservableValue target = SWTObservables.observeSelection(c);
IObservableValue target = ViewersObservables.observeSingleSelection(c_viewer);
IObservableValue model = BeansObservables.observeValue(getInputObject(), "id");
    ctx.bindValue(target, model, null, null);

The binding already works correctly. If the selection in the UI is changed the value in the model is changed, too. But there is NO INITIAL SELECTION!

I really need some help here. Thx in advance!

By the way: If I bind the CCombo and not the Viewer, there is a correct initial selection (see the commented line in the second snippet)! But if I select any other item from the CCombo-box the value of the model is NOT CHANGED!


Solution

  • Okay, I got it now. My code was correct all along. But I didn't realize that my model kept the the observableValue as long. And because the viewer input is an int array it didn't work correctly. All I had to do was simply write a custom UpdateValueStrategy:

    IObservableValue target = ViewersObservables.observeSingleSelection(c_viewer);
    IObservableValue model = BeansObservables.observeValue(getInputObject(), "id");
    
        UpdateValueStrategy u = new UpdateValueStrategy().setConverter(new IConverter() {
    
            @Override
            public Object getFromType() {
                return long.class;
            }
    
            @Override
            public Object getToType() {
                return int.class;
            }
    
            @Override
            public Object convert(Object fromObject) {
                return Integer.parseInt(fromObject.toString());
            }
        });
        ctx.bindValue(target, model, null, u);