Blog
TableViewers and Nativelooking Checkboxes
Many of us have faced the same problem that if you needed to use checkboxes in your TableViewer/TreeViewer they look not native because they are pictures. I had some free minutes and thought that it's time to create a LabelProvider which is able to create platform look-and-feel images out of the box. It's not 100% native but it's not far away. The trick is to automatically create screenshots from CheckBox-Buttons and use them. This way the checkboxes look native on all platforms and correspond to the current look and feel of the platform.
Here's the code if someone is interested:
package at.bestsolution.jface.viewers;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Shell;
public abstract class EmulatedNativeCheckBoxLabelProvider extends ColumnLabelProvider {
private static final String CHECKED_KEY = "CHECKED";
private static final String UNCHECK_KEY = "UNCHECKED";
public EmulatedNativeCheckBoxLabelProvider(ColumnViewer viewer) {
if( JFaceResources.getImageRegistry().getDescriptor(CHECKED_KEY) == null ) {
JFaceResources.getImageRegistry().put(UNCHECK_KEY, makeShot(viewer.getControl().getShell(),false));
JFaceResources.getImageRegistry().put(CHECKED_KEY, makeShot(viewer.getControl().getShell(),true));
}
}
private Image makeShot(Shell shell, boolean type) {
Shell s = new Shell(shell,SWT.NO_TRIM);
Button b = new Button(s,SWT.CHECK);
b.setSelection(type);
Point bsize = b.computeSize(SWT.DEFAULT, SWT.DEFAULT);
b.setSize(bsize);
b.setLocation(0, 0);
s.setSize(bsize);
s.open();
GC gc = new GC(b);
Image image = new Image(shell.getDisplay(), bsize.x, bsize.y);
gc.copyArea(image, 0, 0);
gc.dispose();
s.close();
return image;
}
public Image getImage(Object element) {
if( isChecked(element) ) {
return JFaceResources.getImageRegistry().getDescriptor(CHECKED_KEY).createImage();
} else {
return JFaceResources.getImageRegistry().getDescriptor(UNCHECK_KEY).createImage();
}
}
protected abstract boolean isChecked(Object element);
}
I haven't really tested this (currently only on WinXP) but I suppose it's working on all platforms. You can also get the code from my svn-repository which holds some other interesting utilities and viewer classes.