0

我想验证文本中的输入。确保该值在 0 到 100 之间。但由于某种原因,我无法使用VerifyEvent它。如下,我想在公共无效中获得“检查”值handleEvent(Event event)我该怎么做

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
    }
});
4

1 回答 1

0

好的,所以您想添加 a SWT.Verify,但您不能使用 a VerifyListenerwith VerifyEvent,因此无法访问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;
    }
});

所以你添加ListenertextField. 因此,您不需要该getSource()方法,因为textField来源...

于 2012-08-23T07:34:30.330 回答