Search code examples
javaswttableviewer

Remove a selection listener on a table item


I have a table where multiple table items are available. Out of them, for some table items background and foreground color is set.

On selection of a colored item,since the text color was white, the text is difficult to read So, I need to change the forground color to default ie. black. I had done it using the selection listener

private SelectionListener selectionListener;

    private void mouseTrackListener() {
        selectionListener = new SelectionListener() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                        ((TableItem) e.item).setForeground(null);
                    }
                }
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent e) {

            }
        };

        this.table.addSelectionListener(selectionListener);

        this.table.removeSelectionListener(selectionListener);
    }

And the color got changed successfully.

But now I am selecting any other item which is not colored, so I want to remove the above selection listener and set the text color to colored ie. white. I am not getting how to use this.table.removeSelectionListener.

Can some one please help.


Solution

  • You need to remember the selection listener somewhere, probably a field in the class managing the table.

    private SelectionListener listener;
    
    ...
    
    listener = new SelectionListener() ....
    
    
    ...
    
    table.addSelectionListener(listener);
    
    ...
    
    table.removeSelectionListener(listener);
    

    Be sure to only create the listener once (possibly in the class constructor).

    An alternative is to just add the listener (once) and then test a flag in the listener to decide if you setForeground.