TreeViewer color row alternatively

2019-09-11 18:38发布

问题:

I am new to eclipse SWT. I am trying to override the getBackground method of ITableColorProvider to color rows alternatively of a treeViewer. I was trying coloring with row index (index%2 == 0). It colors all the rows instead.

TreeViewer colors one cell at a time, instead of rows. Any pointers on how to achieve it (alternate row color for treeviewer) or code snippet will be very helpful.

List<TreeItem> treeItems = Arrays.asList( m_viewer.getTree().getItems() );
int index = treeItems.indexOf( element );

if( index % 2 == 0 )
        {
            backgroundColor = Display.getDefault().getSystemColor(
                    SWT.COLOR_YELLOW );
        }
        else
        {
            backgroundColor = Display.getDefault().getSystemColor(
                    SWT.COLOR_GRAY );
        }

回答1:

ITableColorProvider is used for TableViewer , for TreeViewer your class that extends LabelProvider should implement IColorProvider

public class MyLabelProvider extends LabelProvider implements IColorProvider{

        @Override
        public String getText(Object element) {
            //how the label is obtained for an element
        }

        @Override
        public Color getBackground(Object element) {
            if(((TreeItem) element).getId() % 2 == 0) {
                return Display.getCurrent().getSystemColor(SWT.COLOR_BLUE);
            }else{
                return Display.getCurrent().getSystemColor(SWT.COLOR_RED);
            }                   
        }

        @Override
        public Color getForeground(Object element) {
            return null;
        }
    }

The Color Class is the one from org.eclipse.swt.graphics.Color. I supposed that every TreeItem has an id property that is generated cosecutively