在一个基于eclipse RCP的项目上:
使用 SWT 和 eclipse RCP 我想显示与下图完全相同的错误或信息标记。当鼠标指针悬停在错误标记上时,弹出窗口会显示原因。我需要这种能力来向用户显示错误或警告。
在问题视图中同时出现相同的错误会非常好。
在一个基于eclipse RCP的项目上:
使用 SWT 和 eclipse RCP 我想显示与下图完全相同的错误或信息标记。当鼠标指针悬停在错误标记上时,弹出窗口会显示原因。我需要这种能力来向用户显示错误或警告。
在问题视图中同时出现相同的错误会非常好。
1)您需要ControlDecoration
s (代码取自https://krishnanmohan.wordpress.com/2012/10/04/inline-validations-in-eclipse-rcp-field-assists/):
Label label = new Label(parent, SWT.NONE);
label.setText("Please Enter Pincode:");
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
Text txtPincode = new Text(parent, SWT.NONE);
txtPincode.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
//Adding the decorator
final ControlDecoration txtDecorator = new ControlDecoration(txtPincode, SWT.TOP|SWT.RIGHT);
FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry .DEC_ERROR);
Image img = fieldDecoration.getImage();
txtDecorator.setImage(img);
txtDecorator.setDescriptionText("Pls enter only numeric fields");
// hiding it initially
txtDecorator.hide();
txtPincode.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
Text text = (Text)e.getSource();
String string = text.getText();
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
for (int i = 0; i < chars.length; i++) {
if (!('0' <= chars[i] && chars[i] <= '9')) {
txtDecorator.show();
} else {
txtDecorator.hide();
}
}
}
});
显然,您可以使用ModifyListener
orVerifyListener
代替KeyListener
. 但是,为每个字段手动执行此操作会导致大量难以维护的代码。令人惊讶的是,SWT/JFace 没有很好的内置验证解决方案,除非您使用数据绑定(如http://www.toedter.com/blog/?p=36中所述)。您可以编写自己的小框架来简化使用。
2)您需要使用标记,例如
IResource resource = ... // get your specific IResource
resource.createMarker(IMarker.PROBLEM);
marker.setAttribute(IMarker.MESSAGE, message);
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
正确验证字段时,不要忘记删除标记。