Example usage for org.eclipse.jface.databinding.swt.typed WidgetProperties text

List of usage examples for org.eclipse.jface.databinding.swt.typed WidgetProperties text

Introduction

In this page you can find the example usage for org.eclipse.jface.databinding.swt.typed WidgetProperties text.

Prototype

public static <S extends Widget> IWidgetValueProperty<S, String> text(int... events) 

Source Link

Document

Returns a value property for observing the text of a StyledText or Text .

Usage

From source file:org.eclipse.jface.examples.databinding.snippets.Snippet004DataBindingContextErrorLabel.java

License:Open Source License

public static void main(String[] args) {
    final Display display = new Display();
    Realm.runWithDefault(DisplayRealm.getRealm(display), () -> {
        Shell shell = new Shell(display);
        shell.setText("Data Binding Snippet 004");
        shell.setLayout(new GridLayout(2, false));

        new Label(shell, SWT.NONE).setText("Enter '5' to be valid:");

        Text text = new Text(shell, SWT.BORDER);
        WritableValue<String> value = WritableValue.withValueType(String.class);
        new Label(shell, SWT.NONE).setText("Error:");

        Label errorLabel = new Label(shell, SWT.BORDER);
        errorLabel.setForeground(display.getSystemColor(SWT.COLOR_RED));
        GridDataFactory.swtDefaults().hint(200, SWT.DEFAULT).applyTo(errorLabel);

        DataBindingContext dbc = new DataBindingContext();

        // Bind the text to the value.
        dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(text), value,
                new UpdateValueStrategy<String, String>().setAfterConvertValidator(new FiveValidator()), null);

        // Bind the error label to the validation error on the dbc.
        dbc.bindValue(WidgetProperties.text().observe(errorLabel),
                new AggregateValidationStatus(dbc.getBindings(), AggregateValidationStatus.MAX_SEVERITY));

        shell.pack();/*  ww  w .ja  v  a 2  s.  c  om*/
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
    });
    display.dispose();
}

From source file:org.eclipse.jface.examples.databinding.snippets.Snippet008ComputedValue.java

License:Open Source License

/**
 * @param args/*from  w  w  w .  java 2s.co  m*/
 */
public static void main(String[] args) {
    final Display display = new Display();
    Realm.runWithDefault(DisplayRealm.getRealm(display), () -> {
        Shell shell = new Shell(display);
        shell.setLayout(new FillLayout());

        final UI ui = new UI(shell);
        final Data data = new Data();

        // Bind the UI to the Data.
        DataBindingContext dbc = new DataBindingContext();
        dbc.bindValue((IObservableValue<String>) WidgetProperties.text(SWT.Modify).observe(ui.firstName),
                data.firstName);
        dbc.bindValue((IObservableValue<String>) WidgetProperties.text(SWT.Modify).observe(ui.lastName),
                data.lastName);

        // Construct the formatted name observable.
        FormattedName formattedName = new FormattedName(data.firstName, data.lastName);

        // Bind the formatted name Text to the formatted name
        // observable.
        dbc.bindValue((IObservableValue<String>) WidgetProperties.text(SWT.None).observe(ui.formattedName),
                formattedName, new UpdateValueStrategy<String, String>(false, UpdateValueStrategy.POLICY_NEVER),
                null);

        shell.pack();
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
    });
    display.dispose();
}

From source file:org.eclipse.jface.examples.databinding.snippets.Snippet010MasterDetail.java

License:Open Source License

public static void main(String[] args) {
    final Display display = new Display();
    Realm.runWithDefault(DisplayRealm.getRealm(display), () -> {
        Shell shell = new Shell(display);
        shell.setLayout(new GridLayout());

        Person[] persons = new Person[] { new Person("Me"), new Person("Myself"), new Person("I") };

        ListViewer viewer = new ListViewer(shell);
        viewer.setContentProvider(new ArrayContentProvider());
        viewer.setInput(persons);/*from  w w  w  .j ava2  s  .c  o m*/

        Text name = new Text(shell, SWT.BORDER | SWT.READ_ONLY);

        // 1. Observe changes in selection.
        IObservableValue<Person> selection = ViewerProperties.singleSelection(Person.class).observe(viewer);

        // 2. Observe the name property of the current selection.
        IObservableValue<String> detailObservable = BeanProperties.value(Person.class, "name", String.class)
                .observeDetail(selection);

        // 3. Bind the Text widget to the name detail (selection's
        // name).
        new DataBindingContext().bindValue(WidgetProperties.text(SWT.NONE).observe(name), detailObservable,
                new UpdateValueStrategy<>(false, UpdateValueStrategy.POLICY_NEVER), null);

        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
    });
    display.dispose();
}

From source file:org.eclipse.jface.examples.databinding.snippets.Snippet011ValidateMultipleBindingsSnippet.java

License:Open Source License

private static void run() {
    Shell shell = new Shell();

    View view = new View(shell);
    final Model model = new Model();

    DataBindingContext dbc = new DataBindingContext();
    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(view.text1), model.value1,
            new UpdateValueStrategy<String, String>()
                    .setAfterConvertValidator(new CrossFieldValidator(model.value2)),
            null);//from  w ww  .  j  a  v a 2s.  c o  m

    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(view.text2), model.value2,
            new UpdateValueStrategy<String, String>()
                    .setAfterConvertValidator(new CrossFieldValidator(model.value1)),
            null);

    // DEBUG - print to show value change
    model.value1.addValueChangeListener(event -> System.out.println("Value 1: " + model.value1.getValue()));

    // DEBUG - print to show value change
    model.value2.addValueChangeListener(event -> System.out.println("Value 2: " + model.value2.getValue()));

    shell.pack();
    shell.open();
    Display display = shell.getDisplay();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:org.eclipse.jface.examples.databinding.snippets.Snippet015DelayTextModifyEvents.java

License:Open Source License

private static void createControls(Shell shell) {
    final Label field1 = createLabel(shell, SWT.NONE, "Field 1 ");

    Text text1 = new Text(shell, SWT.BORDER);
    GridDataFactory.fillDefaults().grab(true, false).hint(200, SWT.DEFAULT).applyTo(text1);
    createLabel(shell, SWT.NONE, "200 ms delay");

    final Label field2 = createLabel(shell, SWT.NONE, "Field 2 ");

    Text text2 = new Text(shell, SWT.BORDER);
    GridDataFactory.fillDefaults().grab(true, false).hint(200, SWT.DEFAULT).applyTo(text2);

    createLabel(shell, SWT.NONE, "2000 ms delay");

    final ISWTObservableValue<String> delayed1 = WidgetProperties.text(SWT.Modify).observeDelayed(200, text1);
    final ISWTObservableValue<String> delayed2 = WidgetProperties.text(SWT.Modify).observeDelayed(2000, text2);

    // (In a real application,you would want to dispose the resource manager
    // when you are done with it)
    ResourceManager resourceManager = new LocalResourceManager(JFaceResources.getResources());
    final Font shellFont = shell.getFont();
    final Font italicFont = resourceManager
            .createFont(FontDescriptor.createFrom(shellFont).setStyle(SWT.ITALIC));

    final IObservableValue<Boolean> stale1 = Observables.observeStale(delayed1);
    new ControlUpdater(field2) {
        @Override/*from   w w w. ja va  2s . c  o m*/
        protected void updateControl() {
            field2.setFont(stale1.getValue() ? italicFont : shellFont);
        }
    };

    final IObservableValue<Boolean> stale2 = Observables.observeStale(delayed2);
    new ControlUpdater(field1) {
        @Override
        protected void updateControl() {
            field1.setFont(stale2.getValue() ? italicFont : shellFont);
        }
    };

    String info = "Pending changes are applied immediately if the observed control loses focus.";
    GridDataFactory.fillDefaults().span(3, 1).hint(300, SWT.DEFAULT)
            .applyTo(createLabel(shell, SWT.WRAP, info));

    DataBindingContext dbc = new DataBindingContext();

    dbc.bindValue(delayed1, delayed2);

    // Sometimes it is useful to do a manual value flush when of the delayed
    // observables. This can be done in the following two ways.

    text2.addTraverseListener(e -> {
        if (e.detail == SWT.TRAVERSE_RETURN) {
            // The DataBindingContext update methods can also be used to update
            // observables in bulk
            dbc.updateTargets();
        }
    });

    text1.addTraverseListener(e -> {
        if (e.detail == SWT.TRAVERSE_RETURN) {
            // When the setValue method is called on a delayed observable
            // the change is immediately propagated to its listeners without
            // any delay. All other pending changes are cancelled.
            delayed1.setValue(text1.getText());
        }
    });
}

From source file:org.eclipse.jface.examples.databinding.snippets.Snippet019TreeViewerWithListFactory.java

License:Open Source License

protected DataBindingContext initDataBindings() {
    IObservableValue<Bean> treeViewerSelectionObserveSelection = ViewerProperties.singleSelection(Bean.class)
            .observe(beanViewer);/*from  w  w w  .ja  v a2 s . c  om*/
    IObservableValue<String> textTextObserveWidget = WidgetProperties.text(SWT.Modify).observe(beanText);
    IObservableValue<String> treeViewerValueObserveDetailValue = BeanProperties
            .value(Bean.class, "text", String.class).observeDetail(treeViewerSelectionObserveSelection);

    DataBindingContext bindingContext = new DataBindingContext();

    bindingContext.bindValue(textTextObserveWidget, treeViewerValueObserveDetailValue);

    return bindingContext;
}

From source file:org.eclipse.jface.examples.databinding.snippets.Snippet021MultiFieldValidation.java

License:Open Source License

private void bindEvensAndOddsGroup(DataBindingContext dbc) {
    IObservableValue<String> targetField1 = WidgetProperties.text(SWT.Modify).observe(field1Target);
    final IObservableValue<Integer> middleField1 = new WritableValue<>(Integer.valueOf(0), Integer.TYPE);
    dbc.bindValue(targetField1, middleField1);

    IObservableValue<String> targetField2 = WidgetProperties.text(SWT.Modify).observe(field2Target);
    final IObservableValue<Integer> middleField2 = new WritableValue<>(Integer.valueOf(0), Integer.TYPE);
    dbc.bindValue(targetField2, middleField2);

    MultiValidator validator = new MultiValidator() {
        @Override/*from   w w  w  .  j a v  a 2s  .  c o  m*/
        protected IStatus validate() {
            Integer field1 = middleField1.getValue();
            Integer field2 = middleField2.getValue();
            if (Math.abs(field1.intValue()) % 2 != Math.abs(field2.intValue()) % 2)
                return ValidationStatus.error("Fields 1 and 2 must be both even or both odd");
            return null;
        }
    };
    dbc.addValidationStatusProvider(validator);

    IObservableValue<Integer> modelField1 = new WritableValue<>(Integer.valueOf(1), Integer.TYPE);
    IObservableValue<Integer> modelField2 = new WritableValue<>(Integer.valueOf(4), Integer.TYPE);
    dbc.bindValue(validator.observeValidatedValue(middleField1), modelField1);
    dbc.bindValue(validator.observeValidatedValue(middleField2), modelField2);

    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(field1ModelValue), modelField1);
    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(field2ModelValue), modelField2);
}

From source file:org.eclipse.jface.examples.databinding.snippets.Snippet021MultiFieldValidation.java

License:Open Source License

private void bindSumAndAddendsGroup(DataBindingContext dbc) {
    IObservableValue<String> targetSum = WidgetProperties.text(SWT.Modify).observe(sumTarget);
    final IObservableValue<Integer> middleSum = new WritableValue<>(0, Integer.TYPE);
    dbc.bindValue(targetSum, middleSum);

    final IObservableList<Integer> targetAddends = new WritableList<>(new ArrayList<>(), Integer.TYPE);
    addendsTarget.setContentProvider(new ObservableListContentProvider<>());
    addendsTarget.setInput(targetAddends);

    addAddendButton.addSelectionListener(new SelectionAdapter() {
        @Override/*from w w  w. j  ava 2s  .  co m*/
        public void widgetSelected(final SelectionEvent e) {
            InputDialog dialog = new InputDialog(getShell(), "Input addend", "Enter an integer addend", "0",
                    newText -> {
                        try {
                            Integer.valueOf(newText);
                            return null;
                        } catch (NumberFormatException e1) {
                            return "Enter a number between " + Integer.MIN_VALUE + " and " + Integer.MAX_VALUE;
                        }
                    });
            if (dialog.open() == Window.OK) {
                targetAddends.add(Integer.valueOf(dialog.getValue()));
            }
        }
    });

    removeAddendButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            IStructuredSelection selection = addendsTarget.getStructuredSelection();
            if (!selection.isEmpty())
                targetAddends.remove(selection.getFirstElement());
        }
    });

    IObservableValue<Integer> modelSum = new WritableValue<>(Integer.valueOf(5), Integer.TYPE);
    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(sumModelValue), modelSum);

    IObservableList<Integer> modelAddends = new WritableList<>(new ArrayList<>(), Integer.TYPE);

    MultiValidator validator = new MultiValidator() {
        @Override
        protected IStatus validate() {
            int sum = middleSum.getValue();
            int actualSum = 0;
            for (int i : targetAddends) {
                actualSum += i;
            }
            if (sum != actualSum)
                return ValidationStatus.error("Sum of addends is " + actualSum + ", expecting " + sum);
            return ValidationStatus.ok();
        }
    };
    dbc.addValidationStatusProvider(validator);

    addendsModelValue.setContentProvider(new ObservableListContentProvider<>());
    addendsModelValue.setInput(modelAddends);

    dbc.bindValue(validator.observeValidatedValue(middleSum), modelSum);
    dbc.bindList(validator.observeValidatedList(targetAddends), modelAddends);
}

From source file:org.eclipse.jface.examples.databinding.snippets.Snippet026AnonymousBeanProperties.java

License:Open Source License

private void bindUI() {
    ISetProperty<Object, Object> treeChildrenProperty = new DelegatingSetProperty<Object, Object>() {
        ISetProperty<ApplicationModel, ContactGroup> modelGroups = BeanProperties.set(ApplicationModel.class,
                "groups", ContactGroup.class);
        ISetProperty<ContactGroup, Contact> groupContacts = BeanProperties.set(ContactGroup.class, "contacts",
                Contact.class);

        @SuppressWarnings("unchecked")
        @Override/*from w w w . j  av  a 2s. c o  m*/
        protected ISetProperty<Object, Object> doGetDelegate(Object source) {
            if (source instanceof ApplicationModel)
                return (ISetProperty<Object, Object>) (Object) modelGroups;
            if (source instanceof ContactGroup)
                return (ISetProperty<Object, Object>) (Object) groupContacts;
            return null;
        }
    };

    ViewerSupport.bind(contactViewer, model, treeChildrenProperty, BeanProperties.values("name", "status"));

    contactViewer.expandAll();

    final IObservableValue<Object> selection = ViewerProperties.singleSelection().observe(contactViewer);

    DataBindingContext dbc = new DataBindingContext();

    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(nameText),
            BeanProperties.value("name").observeDetail(selection));

    statusViewer.setContentProvider(new ArrayContentProvider());
    statusViewer.setInput(statuses);

    dbc.bindValue(ViewerProperties.singleSelection().observe(statusViewer),
            BeanProperties.value("status").observeDetail(selection));

    dbc.bindValue(WidgetProperties.enabled().observe(statusViewer.getControl()),
            ComputedValue.create(() -> selection.getValue() instanceof Contact));
}

From source file:org.eclipse.jface.examples.databinding.snippets.Snippet027ExternalValidator.java

License:Open Source License

private void bindUI() {
    DataBindingContext dbc = new DataBindingContext();

    final IObservableValue<String> name = BeanProperties.value(Contact.class, "name", String.class)
            .observe(contact);/*from   w  w w.j  a  v a 2 s . c o m*/

    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(nameValue), name, null, null);

    final IObservableValue<String> email = BeanProperties.value(Contact.class, "email", String.class)
            .observe(contact);

    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(emailValue), email, null, null);

    final IObservableValue<String> phone = BeanProperties.value(Contact.class, "phoneNumber", String.class)
            .observe(contact);

    dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(phoneNumberValue), phone, null, null);

    MultiValidator validator = new MultiValidator() {
        @Override
        protected IStatus validate() {

            // Everything accessed here will trigger re-validation.
            name.getValue();
            email.getValue();
            phone.getValue();

            System.out.println("Validating...");

            return contact.validate();
        }
    };
    dbc.addValidationStatusProvider(validator);

    WizardPageSupport.create(this, dbc);
}