I have a (hopefully simple) problem to overcome. If I have a Button that executes a potentially long running method, how can I disable successive presses of that button?
I have hooked into the SelectionListener to first disable the Button, then do the work, followed by re-enabling the Button on its return. However it seems that once the Button becomes disabled I can actually click the button once more and it 'queues' up the selection event until after the first SelectionEvent is finished.
I've taken some demo code to present the scenario. The Button starts a Thread.sleep(5000), and even though my Button is disabled it seems it will still queue up SelectionEvents for processing immediately afterwards.
- Code: Select all
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class Main
{
static Text text;
static Button b;
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.makeColumnsEqualWidth = true;
shell.setLayout(layout);
GridData data = new GridData(GridData.FILL_BOTH);
b = new Button(shell, SWT.PUSH);
b.setText("Push Me");
b.setLayoutData(data);
b.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent event)
{
text.append("Testing Thread Update\n");
b.setEnabled(false);
try
{
Thread.sleep(5000);
}
catch(Exception e)
{
}
text.append("Added something else\n");
b.setEnabled(true);
}
});
data = new GridData(GridData.FILL_BOTH);
text = new Text(shell, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP);
text.setLayoutData(data);
shell.pack();
shell.open();
while(!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
}
Thanks for any advice - the SWT Designer has proven to be a fantastic aid.