How can add validation to an SWT widget? E.g. Text?
I tried both of the following (found online):
txtPort.addListener(SWT.Verify,new Listener() {
@Override
public void handleEvent(Event event) {
String port = ((Text)event.widget).getText();
try{
int portNum = Integer.valueOf(port);
if(portNum <0 || portNum > 65535){
event.doit = false;
}
}
catch(Exception ex){
event.doit = false;
}
}
});
Also:
txtPort.addVerifyListener(new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
String port = ((Text)e.widget).getText();
try{
int portNum = Integer.valueOf(port);
if(portNum <0 || portNum > 65535){
e.doit = false;
}
}
catch(Exception ex){
e.doit = false;
}
}
});
If I add a character, the cursor stucks and I can not even delete it.
Even if I just delete everything the first time, the cursor also stucks and I can not write anything else.
What am I messing up here? How am I supposed to do the validation of a Text?
In this case I only want to accept a number serving as port.
The
VerifyListeneryou are creating will be called before any text has actually been entered. You a currently checking the text that has already been entered to see if the value is valid, but it will never be valid because no text has yet been entered.Try reading the value of
e.textto see if it’s an integer and use thee.startande.endproperties along with the thegetText()you have now to see if the overall new value will be between 0 and 65535.An easier solution may be to create a
ModifyListenerthat only enables a submit button when the Text widget’s text contains a valid port number.You can try something similar to this: