开发您的第一个 Eclipse RCP 应用程序(12/12)

来源:互联网 发布:网络信息安全管理制度 编辑:程序博客网 时间:2024/05/21 22:21
 
前一页第 12 页,共 19 页后一页


对本教程的评价

帮助我们改进这些内容


观察验证错误

所做的更改都是有用的,但是如果在出现验证错误时能够通知用户就更好了。此功能可通过绑定到特定的 observable 来实现。

如果查看 DataBindingContext 类中的 bind() 方法的方法签名,则会发现该方法签名返回了一个 Binding 对象,您到现在为止可能都还没有注意过这个对象。这个 Binding 对象是负责保持数据在模型与目标之间同步。该对象还会在适当的时间调用转换程序和验证程序。每个 Binding 对象还有分别用于部分和完整 ValidatorError 的 observable。可以观察这些数据来确定何时出现了错误。修改 ContactForm 类,添加两个标签以在其中查看结果,然后绑定这两个标签,如清单 18 所示。根据需要修改导入的代码。这段代码依赖于此项目附带的额外软件包中的一些类。



清单 18. 在标签中显示错误
                    ctx.bind(partialValidationErrorLabel, binding        .getPartialValidationError(), new BindSpec(        new ValidationErrorToStringConverter(), /        new ReadOnlyConverter(                String.class, ValidationError.class),         null, null));ctx.bind(validationErrorLabel, binding.getValidationError(),new BindSpec(new ValidationErrorToStringConverter(),        new ReadOnlyConverter(String.class,                ValidationError.class), null, null));. . . Label partialLabel = new Label(c, SWT.NONE);partialLabel.setText("Partial Error:");this.partialValidationErrorLabel = new Label(c, SWT.BORDER);gridData = new GridData(GridData.FILL_HORIZONTAL);this.partialValidationErrorLabel.setLayoutData(gridData);Label fullLabel = new Label(c, SWT.NONE);fullLabel.setText("Validation Error:");this.validationErrorLabel = new Label(c, SWT.BORDER);gridData = new GridData(GridData.FILL_HORIZONTAL);this.validationErrorLabel.setLayoutData(gridData);

在示例运行程序上单击鼠标右键,然后将应用程序作为一个 SWT 应用程序再次运行。应当会看到一个类似图 8 所示的对话框。启用 Years Married 字段,然后输入一个非数字字符。注意显示的错误消息。接下来,尝试输入数字 5,然后按 Tab 键从字段中移出以测试其他验证标签。最后,将标签更改为数字 4。两个错误标签都应当为空,因为未出现过任何验证错误。



图 8. 带有显示验证错误的 UI 示例
带有显示验证错误的 UI 示例 
原创粉丝点击