I need some help, please. I need to run showErrorMessage(errorMessage)
with some delay (2 sec) in separate thread. But if user continues typing and result==true
before showErrorMessage
method runs, I need to stop executing it.
private class DirectoryVarFieldEditor extends DirectoryFieldEditor
{
/**
* Initial path for the Browse dialog.
*/
private File filterPath = null;
public DirectoryVarFieldEditor(String name, String labelText, Composite parent) {
//super( name, labelText, parent );
init(name, labelText);
setErrorMessage(JFaceResources.getString("DirectoryFieldEditor.errorMessage"));
setChangeButtonText(JFaceResources.getString("openBrowse"));
setValidateStrategy(VALIDATE_ON_KEY_STROKE);
createControl(parent);
setEmptyStringAllowed(false);
}
// another code...
@Override
protected boolean doCheckState() {
System.out.println("DirectoryVarFieldEditor.doCheckState()");
String fileName = getTextControl().getText();
fileName = fileName.trim();
fileName = TCA3DNKernel.expandEnvironmentVariables(fileName);
if (fileName.length() == 0 && isEmptyStringAllowed())
return true;
File file = new File(fileName);
return file.isDirectory();
}
//
@Override
protected boolean checkState()
{
boolean result = false;
boolean emptyStringAllowed = super.isEmptyStringAllowed();
Text textField = super.getTextControl();
String errorMessage = getErrorMessage();
if (emptyStringAllowed)
{
result = true;
}
if (textField == null)
{
result = false;
} else
{
String txt = textField.getText();
result = (txt.trim().length() > 0) || emptyStringAllowed;
}
// call hook for subclasses
result = result && doCheckState();
if (result)
{
clearErrorMessage();
} else
{
System.out.println("DirectoryVarFieldEditor.checkState()");
// showErrorMessage method shoud run with delay:
showErrorMessage(errorMessage);
}
return result;
}
// another code...
}
Thanks for any hint!!!
CodePudding user response:
In SWT/JFace you can't call GUI operations on background threads (this is the same in most GUI systems).
For this I would use Display.timerExec
to run a method after the two seconds. Set a flag if the user types something that the method can check. timerExec
runs the code in the UI thread so there are no problems with background threads.
private boolean dataEntered;
...
dataEntered = false;
Display.getCurrent().timerExec(2_000, () -> {
if (!dataEntered && !getTextControl().isDisposed()) {
showErrorMessage("xxx");
}
});
... other code sets dataEntered = true if data is entered
The !getTextControl().isDisposed()
check deals with the dialog being closed before the 2 seconds expires.