DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Java:SWT: Preserve Font Colour When The Row Is Selected
Java:SWT: Preserve font colour when the row is selected
package ca.freewill.swt.test;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.ITableColorProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
/**
* Preserve the font colour of the highlighted line. Note that if the foreground
* colour of the row is the same as the background colour, then the text will
* essentially disappear.
*/
public class ForegroundColourPreserver {
/*
* Support for tables with a single foreground colour, used by all table
* cells.
*/
private static class SingleColorProvider implements ITableColorProvider {
private final Table table;
public SingleColorProvider(Table table) {
this.table = table;
}
public Color getBackground(Object arg0, int arg1) {
return null;
}
public Color getForeground(Object arg0, int arg1) {
return table.getForeground();
}
}
private final ITableColorProvider colorProvider;
/**
* Preserve the table font colour by adding a paint listener to redraw the
* table item text in the expected colour.
*
* Note that the row will be hard to read or illegible if the foreground
* colour is close to the background colour.
*
* @param table
* the table to paint.
*/
public ForegroundColourPreserver(TableViewer tableViewer) {
IBaseLabelProvider labelProvider = tableViewer.getLabelProvider();
if (labelProvider instanceof ITableColorProvider) {
colorProvider = (ITableColorProvider) labelProvider;
} else {
colorProvider = new SingleColorProvider(tableViewer.getTable());
}
tableViewer.getTable().addListener(SWT.PaintItem, new Listener() {
public void handleEvent(Event event) {
ForegroundColourPreserver.this.handleEvent(event);
}
});
}
/*
* Repaint the text. Note the one pixel jog to the right. This may change in
* a subsequent SWT release.
*/
protected void handleEvent(Event event) {
TableItem item = (TableItem) event.item;
event.gc.setForeground(colorProvider.getForeground(item.getData(), event.index));
Rectangle rect = item.getTextBounds(event.index);
event.gc.drawString(item.getText(event.index), rect.x-1, rect.y); // Out-by-one x pixel!
}
}





