如何在SWT小部件旁边显示错误标记?

mor*_*avi 2 java swt eclipse-rcp

在基于eclipse RCP的项目中:

  1. 使用SWT和eclipse RCP我想显示与以下图片完全相同的错误或信息标记.当鼠标指针悬停错误标记时,弹出窗口会显示原因.我需要此功能来向用户显示错误或警告.

  2. 在问题视图中同时出现相同的错误会非常好.

Ale*_*nov 7

1)您需要ControlDecorations(代码取自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();
            }
        }      
    }
});
Run Code Online (Sandbox Code Playgroud)

显然,你可以使用ModifyListenerVerifyListener代替KeyListener.但是,对每个字段手动执行此操作将导致许多令人不愉快的维护代码.令人惊讶的是,除非您使用数据绑定(如http://www.toedter.com/blog/?p=36中所述),否则SWT/JFace没有良好的内置验证解决方案.您可以编写自己的小框架来简化使用.

2)你需要使用标记,例如

IResource resource = ... // get your specific IResource

resource.createMarker(IMarker.PROBLEM);
marker.setAttribute(IMarker.MESSAGE, message);
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
Run Code Online (Sandbox Code Playgroud)

在正确验证字段时,不要忘记删除标记.