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

Ivor has posted 7 posts at DZone. View Full User Profile

Java:SWT: Remove Grid Lines From Empty Rows

02.27.2009
| 1551 views |
  • submit to reddit
        Java:SWT: remove grid lines from empty rows

package ca.freewill.swt.test;

import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

/**
 * Remove grid lines from the unused bottom and right portions of a table.
 */
public class EmptyCellGridLineRemover {

	/*
	 * The grid drawn around a table cell is this many pixels wide.
	 */
	private static final int GRID_WIDTH = 1;

	/**
	 * Remove grid lines from empty table cells by adding a paint listener to
	 * clear unused items at the bottom of the table, and free space to the
	 * right of the last column.
	 * 
	 * @param table
	 *            the table to paint.
	 */
	public EmptyCellGridLineRemover(Table table) {
		table.addPaintListener(new PaintListener() {
			public void paintControl(PaintEvent e) {
				EmptyCellGridLineRemover.this.paintControl(e);
			}
		});
	}

	protected void paintControl(PaintEvent e) {
		Table table = (Table) e.widget;
		e.gc.fillRectangle(getUnusedBottomRectangle(table));
		e.gc.fillRectangle(getUnusedRightRectangle(table));
	}

	/*
	 * Get the unused bottom portion of the table area.
	 */
	private Rectangle getUnusedBottomRectangle(Table table) {
		Rectangle tableArea = table.getClientArea();
		if (table.getItemCount() > 0) {
			TableItem item = table.getItem(table.getItemCount() - 1);
			Rectangle lastItemBounds = item.getBounds();
			int yDelta = lastItemBounds.y + lastItemBounds.height + GRID_WIDTH;
			tableArea.y += yDelta;
			tableArea.height -= yDelta;
		}
		return tableArea;
	}

	/*
	 * Get the unused bottom portion of the table area.
	 */
	private Rectangle getUnusedRightRectangle(Table table) {

		int totalColumnWidth = GRID_WIDTH; // Allow for grid line of last column

		TableColumn[] columns = table.getColumns();
		for (int i = 0; i < columns.length; ++i) {
			totalColumnWidth += columns[i].getWidth();
		}

		Rectangle tableArea = table.getClientArea();
		tableArea.x += totalColumnWidth;
		tableArea.width -= totalColumnWidth;
		return tableArea;
	}

}