I am working on a program that uses two tables. The first table has a selection listener that add new items to the second table. Depending on the value of the first table, I want another selection listener added to the second table. If the value is something else, I want the selection listener to be removed. I can get the selection listener to be added to the second table, but I cannot seem to remove it. If the first table requires the second table to have the selection listener, and the selection listener appears to be doubled.
tblFirst.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent arg0) {
TableItem ti = tblFirst.getSelection()[0];
String selectedText = ti.getText();
SelectionListener myListener = new SelectionListener(){
@Override
public void widgetSelected(SelectionEvent arg0) {
//do something here
}
}
if(selectedText.equals("sometext")) {
tblSecond.removeSelectionListener(myListener);
tblSecond.addSelectionListener(myListener);
}
}
With the above example, the SelectionListener is added each time I select an item with text “sometext”. If I selected the item three times, the SelectionListener is fired three times. The removeSelectionListener is not removing the selectionlistener first.
How do I make this work?
myListenerrefers to a new instance and not the one that was created and added the last time. If you create a new instance each time and don’t keep a reference to it, you can’t remove it. CreatemyListenerjust once outside of the selection handler method.Although, the whole adding and removing of listener seems like a kludge – you should instead have some condition in the second listener to decide whether to react to selection change or not.