Eclipse JFace tip: How to add column headers to a TableViewer

So you’ve created a JFace TableViewer, via:

TableViewer tableViewer = new TableViewer(parent);

The scenario: You have already set up the label provider, the content provider and the (model) input. The label provider, which extends ITableLabelProvider returns values for two columns. The data is showing up nicely, but you don’t see any APIs in TableViewer to set column headers.

The key to understanding the problem is realizing that the Swing API != JFace API. It is more like Swing = JFace + SWT. Yes, I know that technically Swing sits on top of AWT, but in practice, most of the AWT APIs have been superceded by Swing, so most of the time when you deal with Swing, you’re dealing with a JSomething. In fact, you know if the code is bad if it uses a lot of non JSomethings.

On the other hand, Eclipse has more than one dedicated project teams dedicated to UI development that have well defined boundaries. The SWT team builds the widgets which either wrapper or emulate native widgets. They also build the supporting structures around these, like Drag and Drop. The JFace team wrappers these SWT widgets to let programmers work with them in Model-View-Controller (MVC) way. The JFace team is careful not to duplicate any of the SWT work. There’s also GEF, which I won’t cover in this post.

This JFace and SWT partnership leads to some confusion, since programmers can access both APIs. Swing/AWT programmers can also access both APIs, but in practice, 80% of the code uses the Swing APIs. (With notable exceptions for the various Layouts and Graphics2D.) When using JFace and SWT, there is greater usage of SWT. So AWT has a List which is not used in practice and Swing has a JList which supersedes it. In contrast, SWT has a List and JFace has a ListViewer, which uses that List. If you need to do view-specific stuff, you access the SWT List inside of the JFace ListViewer.

This leads us to the solution to our problem of adding column headers to a JFace TableViewer: You need to get the table (which is playing the View of MVC), add the column headers to it, and also tell it to show its headers.

Here’s code that illustrates how to do this:

// Get the SWT Table that's inside the TableViewer
Table table = tableViewer.getTable();
// Add a column header named "Column 1" that's left justified TableColumn column = new TableColumn(table, SWT.LEFT); column.setText("Column 1"); column.setWidth(100);
// Add a column header named "Column 2" that's left justified TableColumn column2 = new TableColumn(table, SWT.LEFT); column2.setText("Column 2"); column2.setWidth(100);
// Show the column headers table.setHeaderVisible(true);

One Reply to “Eclipse JFace tip: How to add column headers to a TableViewer”

  1. Thanks a lot for the snippet! It helped me understand a basic concept in Eclipse that I was hunting around for more than a week!

Comments are closed.