Monday, September 8, 2008

Problems with enabling/disabling a button ???

I had big problem in solving problem with enabling/disabling a SWT button.my sample code is as follows:

checkButton = new Button(composite,SWT.NONE);
checkButton.setEnabled(false);
checkButton .addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
if(selection.size()!=0){
checkButton.setEnabled(true);
executeEditFuntionality();
}else{
checkButton.setEnabled(false);
}
}
});

To my surprise , when it enters else condition ,its disabling the button forever!!!i mean once its disabled..even if i select anything in viewer , button is not enabled.
I broke my head to solve this..did hours of googling and finally asked one of my genious team mate and he told me that i should be doing enabling/disabling of a widget in the viewers selection changed listener event..I tried that and to my surprise it worked..
below is the sample code

checkButton = new Button(composite,SWT.NONE);
checkButton.setEnabled(false);
checkButton .addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
if(selection.size()!=0){
executeEditFuntionality();
}else{
// do nothing
}
}
});

tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
if(selection.size()!=0){
editButton.setEnabled(true);
}else{
editButton.setEnabled(false);
}
}
});

No comments: