我如何使用来自[org.eclipse.swt.widgets.Event]的事件的getsource()

时间:2012-08-23 02:02:34

标签: java eclipse swt verify

我想验证Text.make中的输入,确保该值介于0和100之间。但由于某种原因,我无法使用VerifyEvent来执行此操作。如下,我想在public void handleEvent(Event event)中获得“check”值我该怎么做

control.addListener (SWT.Verify, new Listener () {
    public void handleEvent(VerifyEvent e) {
        // TODO Auto-generated method stub
        Text text = (Text)e.getSource();
        String t = text.getText();
        String check = t.substring(0, e.start) + e.text + t.substring(e.end);
        e.doit = validateInput(check);
    }
    @Override
    public void handleEvent(Event event) {
        // TODO Auto-generated method stub
    }
});

1 个答案:

答案 0 :(得分:0)

好的,您要添加SWT.Verify,但不能将VerifyListenerVerifyEvent一起使用,因此无法访问event.getSource()。但是,由于您手动添加Listener,因此您知道来源:

final Text textField = new Text(shell, SWT.BORDER);
textField.addListener(SWT.Verify, new Listener() {
    @Override
    public void handleEvent(Event e) {
        // You can access textField, since it is final
        final String oldS = textField.getText();
        String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);

        boolean isValid = true;

        if("".equals(newS))
        {
        }
        else
        {
            try
            {
                // first check, if text really is a number
                float value = Float.parseFloat(newS);

                // then check if it's between 0 and 100
                if(value < 0 || 100 < value)
                    isValid = false;
            }
            catch(NumberFormatException ex)
            {
                isValid = false;
            }
        }

        // if text is not a valid number, prevent user input
        if(!isValid)
            e.doit = false;
    }
});

因此,您将Listener添加到textField。因此,您不需要getSource()方法,因为textField是源...