1. Introduction to NatTable

1.1. What is NatTable?

NatTable is a framework to create table, grid and tree controls. It can handle very large data sets and supports sorting, filtering, grouping and fixed/frozen columns and rows and other advanced features. NatTable is also fully stylable.

Why is it called NatTable?

The original implementation was dedicated to the girlfriend of the creator whose name was Natalie. The implementation was refactored many times, but the name stayed. Today Nat stands for Not a(nother) table, because NatTable is a framework for rich table, grid and tree controls and not just another table widget. Lars Vogel approved this acronym when he first saw it at a conference and shouted Oh No! Not Another Table widget.

1.2. Bundles and dependencies

The NatTable project is split into core and extensions.

The core contains all the interface definitions and common implementations. It has the following dependencies:

  • SWT - rendering and interaction (key, mouse)

  • JFace - resource handling and dialogs

  • org.eclipse.equinox.common & org.eclipse.core.commands - JFace dependencies

  • SLF4J API - internal logging

  • Eclipse Collections - improved internal handling and processing of primitive collections

The extensions category contains special implementations of core functionality using third-party libraries. There are four extensions:

  1. The Eclipse 4 extension contains CSS styling capabilities using the Eclipse CSS engine. It also contains e4 specific implementations like for example the E4SelectionListener to support selection handling the e4 way.

  2. The GlazedLists extension contains implementations for sorting, filtering and trees using the GlazedLists library. It also contains the GroupBy feature which is currently not available in NatTable Core. The GlazedLists Extension has an additional dependency to Apache Commons Codec, which is needed for serialization purposes.

  3. The Nebula extension contains implementations for integrating widgets from the Nebula project. Currently it only contains an ICellEditor and an ICellPainter that uses the RichText control and a CDateTime cell editor.

  4. The Apache POI extension contains implementations for Excel exports using the Apache POI library. It adds support for advanced export features.

1.3. Available update sites and Maven coordinates

Add NatTable to your target platform via a p2 update site from the NatTable download page. These update sites are available.

// Update site for the 2.7.0 release
https://download.eclipse.org/nattable/releases/2.7.0/repository/

// Latest snapshot
https://download.eclipse.org/nattable/snapshots/latest/repository/

The release is also available on Maven Central. The core is in the artifact org.eclipse.nebula.widgets.nattable:org.eclipse.nebula.widgets.nattable.core, the extensions use the same group id and are named extension.glazedlists, extension.e4, extension.nebula and extension.poi. These dependencies are enough for the examples of this tutorial in a plain SWT application.

<dependency>
  <groupId>org.eclipse.nebula.widgets.nattable</groupId>
  <artifactId>org.eclipse.nebula.widgets.nattable.core</artifactId>
  <version>2.7.0</version>
</dependency>
<dependency>
  <groupId>org.eclipse.nebula.widgets.nattable</groupId>
  <artifactId>org.eclipse.nebula.widgets.nattable.extension.glazedlists</artifactId>
  <version>2.7.0</version>
</dependency>

The SWT library for your operating system, for example org.eclipse.platform:org.eclipse.swt.gtk.linux.x86_64, must be added to the classpath of a plain Java application.

2. NatTable example application

2.1. Exploring the NatTable capabilities

NatTable provides an example application that demonstrates almost every feature. It shows the examples in a tree on the left and opens the selected example on the right.

NatTable examples application with the example tree on the left and an example on the right

Via the View Source link at the bottom of the example, you can open the source code of the example.

The tree currently contains three main sections:

  • Tutorial Examples
    The examples that are referred to in upcoming tutorials.

  • Classic Examples
    The examples that exist for a long time.

  • E4 Examples
    Examples to show the use of E4 mechanisms like CSS styling or the E4 selection mechanism.

The E4 Examples are not available in the plain SWT version of the NatTable examples application.

2.2. Starting the example application

You can start the NatTable examples application in three ways. All of them are available in the release folder of the NatTable 2.7.0 download area and are linked from the NatTable examples page.

The easiest way is to download the Eclipse RCP version of the examples application for your operating system. Unpack the downloaded archive and start the application via the executable.

The second option is to download the NatTableExamples.jar file and start it via the command line. The JAR file does not contain the platform-specific SWT libraries. Therefore, you need to add the SWT jar file for your platform to the classpath when starting the examples application.

For starting the NatTable examples application on Linux you would put the org.eclipse.swt.gtk.linux.x86_64 jar next to the NatTableExamples.jar file and call the following command.

java -cp org.eclipse.swt.gtk.linux.x86_64-3.135.0.jar:NatTableExamples.jar org.eclipse.nebula.widgets.nattable.examples.NatTableExamples

On Windows you use the org.eclipse.swt.win32.win32.x86_64 jar and ; as the classpath separator.

The third option is to run the examples application from the sources. Check out the sources from Git as explained in the NatTable wiki. Afterwards, start the org.eclipse.nebula.widgets.nattable.examples.NatTableExamples main class in the org.eclipse.nebula.widgets.nattable.examples project.

3. Exercise: Install NatTable into your IDE

Open the Help  Install New Software…​ and enter https://download.eclipse.org/nattable/releases/2.7.0/repository/ in the Work with: field. The expected output is shown in the screenshot below.

Install dialog listing the NatTable features of the 2.7.0 update site

Select all items and finish the installation. Restart the Eclipse IDE after the installation.

4. Architecture

The architecture of NatTable supports flexible composition and configuration. The following sections explain layers, configurations, commands, events and the label concept for conditional configuration.

4.1. Basics and Limitations

NatTable is a virtual table as it processes only the current visible part of the table. This allows handling large data sets, as only the visible elements are drawn.

The default implementations operate on data that resides in memory. Data that must be fetched on demand needs custom implementations.

NatTable can handle max int rows * max int columns, because the implementation uses Integer based indices.

4.1.1. Comparison to other table widgets

Unlike the SWT Table control, NatTable doesn’t use the native table control of the operating system. It extends the SWT Canvas class and paints its visible part using the Canvas API. Therefore, NatTable does not have the limitations of native controls, like the missing ability to show different row heights in one table (an issue on Windows). JFace tables also create many more objects than NatTable.

NatTable does not support JFace data binding. Its data providers operate directly on the data model, and its own conversion and validation mechanisms fit its concepts better.

4.2. Layers

A NatTable instance is typically built from several ILayer layers. A layer is a rectangular region of cells and has methods to access columns, rows, width and height. Basic features are implemented in a layer and are added to the table by using a layer stack or a layer composition. For example, to add the ability to select cells in a table you can stack a SelectionLayer on top of your data layer.

The following diagram shows the stacking and composing of a NatTable grid.

Diagram of a NatTable grid built from stacked layers and composed regions

4.2.1. Layer stacks and compositions

Layers can be stacked to combine multiple features in a NatTable instance. The DataLayer is mandatory and needs to be the bottom most layer in the stack.

The other layers are created on top of another layer.

You can also use layer compositions where several layers or layer stacks are positioned side by side. A grid, for example, is a common composition that consists of four regions: corner, column header, row header and body, where every region contains separate layer stacks.

4.2.2. Position-Index transformation

By stacking a layer on top of another layer, it is possible to expose a transformed view of its underlying layer cell structure. A transformed view for example can be used to hide or reorder columns.

Columns and rows in a layer can be referenced either by position or by index.

  • The position of a column/row in a layer corresponds to the location of the column/row in the CURRENT layer. Positions always start from 0 and increase sequentially.

  • The index of a column/row in a layer corresponds to the location of the column/row in the LOWEST level layer in the layer stack. Indexes are not necessarily ordered, and in some cases may not even be unique within a layer above the lowest level layer.

These concepts are illustrated by the following example. The layer stack shows a ColumnHideShowLayer that is stacked on top of a ColumnReorderLayer which is in turn stacked on a DataLayer. The positions in the DataLayer are the same as its indexes, because it is the lowest level layer in the stack. The ColumnReorderLayer reorders column 0 of its underlying layer after column 2 of its underlying layer. The ColumnHideShowLayer hides the first column of its underlying layer.

ColumnHideShowLayer
0 1 2 3 4 <- column positions
2 0 3 4 5 <- column indexes


ColumnReorderLayer
0 1 2 3 4 5 <- column positions
1 2 0 3 4 5 <- column indexes


DataLayer
0 1 2 3 4 5 <- column positions
0 1 2 3 4 5 <- column indexes
Usually, the framework does the necessary position-index transformations. So typically, it is not necessary to perform that transformation manually. In the few cases where it might be necessary, you can have a look at the LayerUtil helper class that provides some static methods for that purpose.

4.3. Configuration

NatTable uses configurations to customize the styling and behavior of layers and table. Every layer typically brings configurations for its features.

Configurations are registered via registries. There are two configuration registries for each NatTable instance:

  • IConfigRegistry: Contains configuration attributes, like styling, editing or layer specific configurations.

  • IUiBindingRegistry: Contains UI bindings for mouse and keyboard interactions.

It is recommended to create separate configuration classes to encapsulate the different configurations. It is also possible to put configurations directly into a registry which is mostly used for dynamic behavior changes at runtime. There are four types of configuration classes:

  • AbstractRegistryConfiguration: Used to register configuration values to the IConfigRegistry.

  • AbstractUiBindingConfiguration: Used to bind actions to UI interactions via IUiBindingRegistry.

  • AbstractLayerConfiguration: Used to configure an ILayer. This typically means to register ILayerCommandHandler and ILayerEventHandler on a layer.

  • AggregateConfiguration: Used to combine several configurations in one, for example for styling and UI bindings at once. Several default configurations of NatTable are `AggregateConfiguration`s.

The following simplified UML diagram shows the relationship between configurations, the NatTable and layers.

Simplified UML diagram of the NatTable configuration classes

Editing support is specified via configuration. There is no layer that needs to be added to the layer stack to enable editing.

When creating a NatTable instance with auto configuration turned on, internally the DefaultNatTableStyleConfiguration is added and NatTable#configure() is called automatically to build up the registries. In such a case configuration instances can only be added to layers before the NatTable instance is created. Adding configurations to layers afterwards will not have an effect. Trying to add configuration instances to the NatTable instance will result in an IllegalStateException.

Turn the auto configuration off with the constructor parameter autoconfigure set to false. Then you can add configuration instances to layers and the NatTable instance until you call NatTable#configure(). Afterwards no further configuration instances can be added, because they are interpreted only once to build up the registries.

You can still modify, add, remove or exchange configuration values at runtime directly in the registries.

In case the auto configuration of NatTable is disabled, add at least the DefaultNatTableStyleConfiguration or an equivalent one. Otherwise, the rendering breaks because of missing configuration attributes.

The following listing demonstrates the creation of a NatTable instance with auto configuration turned off.

// create a NatTable using a GridLayer and configure to not using the default configurations
NatTable natTable = new NatTable(parent, gridLayer, false);

// add the default style configuration
natTable.addConfiguration(new DefaultNatTableStyleConfiguration());

// add additional custom configurations
...

// call NatTable#configure() to start the configuration process
natTable.configure();

Some layers need the reference to the IConfigRegistry as constructor parameter. This is because there is no global context, and layers have no reference to the NatTable instance they belong to.

The following listing demonstrates the pattern for creating a NatTable instance that uses an externally created IConfigRegistry.

// create a ConfigRegistry that can be used to create advanced layers
ConfigRegistry configRegistry = new ConfigRegistry();

// create some layers
...

// create a NatTable using a GridLayer and configure to not using the default configurations
NatTable natTable = new NatTable(parent, gridLayer, false);

// set the ConfigRegistry to the NatTable instance BEFORE additional configuration are added
natTable.setConfigRegistry(configRegistry);

// add the default style configuration
natTable.addConfiguration(new DefaultNatTableStyleConfiguration());

// add additional custom configurations
...

// call NatTable#configure() to start the configuration process
natTable.configure();

4.4. Cell display mode

A cell can be displayed in several modes, called DisplayMode. This allows different configurations for the same cell in different modes. The following table lists the display modes.

Table 1. NatTable DisplayModes
DisplayMode Description

DisplayMode#NORMAL

The normal state a cell is in if no other state applies.

DisplayMode#SELECT

The cell is selected.

DisplayMode#EDIT

The cell is edited.

This DisplayMode is never applied to a cell and is only used for configuration purposes!

DisplayMode#HOVER

The mouse hovers over the cell.

DisplayMode#SELECT_HOVER

The mouse hovers over a selected cell.

4.5. Configuration by labels

NatTable supports conditional configuration via labels. Every cell has a LabelStack, which is a collection of Strings, and you register configurations for labels. This ties configurations to specific cells, for example an error style or a checkbox editor for boolean values.

The following listing shows an example that registers an ImagePainter for the label myImageLabel. Further details on registering configuration attribute values are described in Configuration attributes.

configRegistry.registerConfigAttribute(
    CellConfigAttributes.CELL_PAINTER,
    new ImagePainter(),
    DisplayMode.NORMAL,
    "myImageLabel");

The following sections describe how labels are added to the LabelStack of a cell.

When using a CompositeLayer it is possible to set a region label per composition region. You can think of the region label as a default label that is applied to every cell in the corresponding region, e.g., every cell in the body region of a grid has the label GridRegion.BODY in its LabelStack.

Every layer can add labels to the label stack of a cell in ILayer#getConfigLabelsByPosition(int, int). This adds layer specific styling, e.g., a sort indicator in the column header cells of the SortHeaderLayer. Custom labels come from an IConfigLabelAccumulator, which you set on a layer with AbstractLayer#setConfigLabelAccumulator(IConfigLabelAccumulator).

4.5.1. Add custom labels by standard criteria

NatTable ships with AbstractOverrider implementations that register labels for special criteria.

Table 2. AbstractOverrider implementations
AbstractOverrider implementation Description

CellOverrideLabelAccumulator

Registers a label that is applied in case the specified value is shown in the specified column. registerOverride(Object cellValue, int col, String configLabel)

ColumnOverrideLabelAccumulator

Register labels that will be added to the label stack of cells in the column of the specified index. registerColumnOverrides(int columnIndex, String…​ configLabels) registerColumnOverridesOnTop(int columnIndex, String…​ configLabels)

RowOverrideLabelAccumulator

Register labels that will be added to the label stack of cells in the row of the specified index. registerRowOverrides(int rowIndex, String…​ configLabels)

4.5.2. Add column position based default labels

The ColumnLabelAccumulator is a simple implementation that adds column based labels to the label stack. The labels follow the pattern COLUMN_ + column position. Concatenate the constant ColumnLabelAccumulator#COLUMN_LABEL_PREFIX with the column position to register configurations for these labels.

4.5.3. Add custom labels by custom criteria

If the default implementations do not match, implement IConfigLabelAccumulator#accumulateConfigLabels(LabelStack, int, int) and add labels to the given LabelStack. LabelStack#addLabel(String) adds a label at the end of the stack. LabelStack#addLabelOnTop(String) adds it at the first position, which gives it a higher priority.

Another layer or accumulator can still add a label on top afterwards.

The following IConfigLabelAccumulator uses the body data provider to retrieve the object of the current row.

// add labels to provide conditional styling
bodyDataLayer.setConfigLabelAccumulator(new IConfigLabelAccumulator() {
    @Override
    public void accumulateConfigLabels(
        LabelStack configLabels, int columnPosition, int rowPosition) {

        Task task = bodyDataProvider.getRowObject(rowPosition);
        if (task != null && task.isDone()) {
            configLabels.addLabel("doneLabel");
        }
    }
});

Set the IConfigLabelAccumulator on the DataLayer. As the bottom-most layer it needs no index-position transformation, because index == position.

4.5.4. Add multiple labels

A layer takes only one IConfigLabelAccumulator. To use several, combine them with the AggregateConfigLabelAccumulator, which is itself an IConfigLabelAccumulator.

4.6. Configuration attributes

The IConfigRegistry is the registry for typed configuration attributes of a NatTable instance. Apart from UI bindings and special layer configurations, almost every customization is a registered value for a configuration attribute, for example styling, editing, a summary row or the Excel export.

A configuration attribute is a ConfigAttribute<T>, where the generic specifies the value type.

The following code specifies for example a configuration attribute for the value type org.eclipse.swt.graphics.Color.

ConfigAttribute<Color> GRID_LINE_COLOR = new ConfigAttribute<Color>();

The supported default configuration attributes are defined as constants at several places, e.g., CellConfigAttributes or EditConfigAttributes.

4.6.1. Register configuration attributes

Configuration attribute values can be registered by calling one of the available registerConfigAttribute() methods on IConfigRegistry. As ConfigAttribute<T> is generic, the registration is type safe.

Call registerConfigAttribute() within an IConfiguration for the initial configuration, or at runtime for dynamic changes. Changes outside an IConfiguration must happen after NatTable#configure(), because configure() adds the values of the IConfiguration instances and could override manual values.

To register a value, specify the ConfigAttribute<T> and the value. Optionally add the DisplayMode and a label. See Cell display mode and Configuration by labels for further information on that.

Without a DisplayMode, the value is registered for DisplayMode#NORMAL.

The following snippet shows some examples for registering configuration attribute values.

// register a global default style
configRegistry.registerConfigAttribute(
    CellConfigAttributes.CELL_STYLE,
    cellStyle);

// register a global style for selected cells
configRegistry.registerConfigAttribute(
    CellConfigAttributes.CELL_STYLE,
    selectionCellStyle,
    DisplayMode.SELECT);

// register a conditional style a custom label
configRegistry.registerConfigAttribute(
    CellConfigAttributes.CELL_STYLE,
    customCellStyle,
    DisplayMode.NORMAL,
    "myLabel");

4.6.2. Unregister configuration attributes

Configuration attribute values can be unregistered by calling one of the available unregisterConfigAttribute() methods on IConfigRegistry.

Unregistering is typically used to change a configuration at runtime or to modify a default configuration.

Unregister values outside an IConfiguration after NatTable#configure(). Otherwise, the values might not be registered yet and are added afterwards.

4.6.3. Determine the configuration attribute value

Several values can be registered for the same attribute with different DisplayMode and label combinations. The following search determines the value to use.

  • Determine the IDisplayModeOrdering for the current DisplayMode.

  • Iterate over the DisplayMode`s specified by the found `IDisplayModeOrdering.

  • For every DisplayMode, iterate over the labels in a LabelStack and search for a configuration attribute value. If no value is found for a DisplayMode and label combination, check for a value that is registered only for the DisplayMode.

The first value that is found for a DisplayMode and label combination will be used.

The following gives an example on the determination of a configuration attribute value. The value (e.g., a style) is searched for a cell that is selected and has the LabelStack [COLUMN_3, myLabel].

The IDisplayModeOrdering for DisplayMode#SELECT is [SELECT, NORMAL]. Therefore, the search order is:

  • DisplayMode#SELECT && label == COLUMN_3

  • DisplayMode#SELECT && label == myLabel

  • DisplayMode#SELECT

  • DisplayMode#NORMAL && label == COLUMN_3

  • DisplayMode#NORMAL && label == myLabel

  • DisplayMode#NORMAL

4.7. Commands & Events

Interactions in NatTable are implemented using a special command and event pattern.

Diagram of a command going down and an event going up the layer stack

Every UI interaction triggers a command that is transported down the layer stack until a handler takes the command and performs several corresponding actions. Typically the command gets consumed when it is handled which means it is not passed further down the layer stack. There are a few exceptions to that rule for some internal commands that need to get handled in several places, e.g., ClientAreaResizeCommand.

After the command is executed, an event is fired that is transported up the layer stack, giving every layer and every listener the ability to react on possible structural or visual state changes that are the result of the command processing. Events are never consumed and will always be transported to the top of the layer stack.

NatTable is executing commands on user interactions by registering actions to UI interactions. If actions on a NatTable instance should be performed programmatically by pressing a button outside the NatTable instance, e.g., hiding several columns or triggering a visual refresh, the NatTable commands can also be created and processed programmatically.

natTable.doCommand(new VisualRefreshCommand());

4.8. Configuring the NatTable column width

A NatTable should typically span its columns over the full width of its view. The default column width does not do that.

Table 3. Methods to change the column width
Method Description

setColumnWidthByPosition(int columnPosition, int width)

Set a fixed column width for a specific column

setColumnWidthByPosition(int columnPosition, int width, boolean fireEvent)

Set a fixed column width for a specific column and fire a ColumnResizeEvent for updating the NatTable immediately.

setColumnPercentageSizing(boolean percentageSizing)

Activate the percentage sizing for the whole table

setColumnPercentageSizing(int position, boolean percentageSizing)

Activate the percentage sizing for a specific column

setColumnWidthPercentageByPosition(int columnPosition, int width)

Set the percentage value of a certain column, after activating percentage sizing for this column

These column width methods can be used like this:

DataLayer dl = new DataLayer(dataProvider);
// activate percentage sizing for all columns
dl.setColumnPercentageSizing(true);
// deactivate percentage sizing for the first column
dl.setColumnPercentageSizing(0, false);
// apply a fixed size for the first column without percentage sizing
dl.setColumnWidthByPosition(0, 100);

// Use percentage values for the rest of the table
dl.setColumnWidthPercentageByPosition(1, 40);
dl.setColumnWidthPercentageByPosition(2, 60);

5. Data Access

The first step is to configure how the data is provided. For the layer architecture this means using the DataLayer as the bottom-most layer of a layer stack.

5.1. Providing data to the DataLayer

A DataLayer needs an IDataProvider, the connection between the model and NatTable. It provides the number of columns and rows and grants access to the model via column and row index. The interface looks like this.

public interface IDataProvider {

    Object getDataValue(int columnIndex, int rowIndex);
    
    void setDataValue(int columnIndex, int rowIndex, Object newValue);
    
    int getColumnCount();
    
    int getRowCount();
}

Implementing an IDataProvider for a custom data structure is straightforward. The following example shows data from a two-dimensional array.

class TwoDimensionalArrayDataProvider implements IDataProvider {

    private String[][] data;
    
    public TwoDimensionalArrayDataProvider(String[][] data) {
        this.data = data;
    }
    
    @Override
    public Object getDataValue(int columnIndex, int rowIndex) {
        return this.data[columnIndex][rowIndex];
    }

    @Override
    public void setDataValue(int columnIndex, int rowIndex, Object newValue) {
        this.data[columnIndex][rowIndex] = newValue != null ? newValue.toString() : null;
    }

    @Override
    public int getColumnCount() {
        return this.data.length;
    }

    @Override
    public int getRowCount() {
        return this.data[0] != null ? this.data[0].length : 0;
    }
}

The above example is based on the NatTable Examples Application Tutorial Examples  Data  CustomDataProviderExample

5.2. Providing data stored in a list

The data of a NatTable is typically stored in a list, because of ordering and index based access. For this case NatTable provides the ListDataProvider, an IRowDataProvider that uses the list index as the row index. An IColumnAccessor defines which model property is shown per column. Create a ListDataProvider with the list and an IColumnAccessor.

List<Person> persons = ...;

IColumnPropertyAccessor<Person> columnPropertyAccessor = ...;

IDataProvider bodyDataProvider = new ListDataProvider<Person>(
        persons, columnPropertyAccessor);

5.3. Mapping properties to columns

The IColumnAccessor defines how to access the properties of the model elements and how they map to column positions. It is similar to the IDataProvider, but operates on an object and a column index instead of row and column index.

public interface IColumnAccessor<T> {
    
    Object getDataValue(T rowObject, int columnIndex);
    
    void setDataValue(T rowObject, int columnIndex, Object newValue);
    
    int getColumnCount();
}

The following example shows the first name of a Person in column 0 and the last name in column 1.

class PersonColumnAccessor implements IColumnAccessor<Person> {

    @Override
    public Object getDataValue(Person rowObject, int columnIndex) {
        switch (columnIndex) {
            case 0:
                return rowObject.getFirstName();
            case 1:
                return rowObject.getLastName();
        }
        return "";
    }

    @Override
    public void setDataValue(Person rowObject, int columnIndex, Object newValue) {
        switch (columnIndex) {
            case 0:
                rowObject.setFirstName((String)newValue);
                break;
            case 1:
                rowObject.setLastName((String)newValue);
                break;
        }
    }

    @Override
    public int getColumnCount() {
        return 2;
    }
}

5.4. Mapping property names to columns

The IColumnPropertyResolver maps between the property name in the backing bean and the column index. The framework uses it internally, for example for sorting with GlazedLists. It adds these methods.

public interface IColumnPropertyResolver {
    
    String getColumnProperty(int columnIndex);
    
    int getColumnIndex(String propertyName);
}

You rarely implement an IColumnPropertyResolver directly. Implement an IColumnPropertyAccessor instead, which combines IColumnAccessor and IColumnPropertyResolver. To extend the PersonColumnAccessor from above, add the methods shown below.

public static final String[] PERSONWITHADDRESS_PROPERTY_NAMES = {
    FIRSTNAME_PROPERTYNAME,
    LASTNAME_PROPERTYNAME
};

@Override
public String getColumnProperty(int columnIndex) {
    return PERSONWITHADDRESS_PROPERTY_NAMES[columnIndex];
}

@Override
public int getColumnIndex(String propertyName) {
    return Arrays.asList(PERSONWITHADDRESS_PROPERTY_NAMES).indexOf(propertyName);
}

NatTable ships with two IColumnPropertyAccessor implementations that use reflection: the ReflectiveColumnPropertyAccessor and the ExtendedReflectiveColumnPropertyAccessor.

5.5. Access properties via reflection

The ReflectiveColumnPropertyAccessor accesses the properties of a model object via reflection. A String array constructor parameter defines the columns and their order.

String[] propertyNames = {"firstName", "lastName", "gender", "married", "birthday"};

IColumnPropertyAccessor<Person> columnPropertyAccessor =
    new ReflectiveColumnPropertyAccessor<Person>(propertyNames);

The ReflectiveColumnPropertyAccessor follows the Java property specification. Every attribute needs a getter and a setter with the usual names, for example firstName, getFirstName() and setFirstName().

5.6. Extended access to properties via reflection

The ReflectiveColumnPropertyAccessor accesses only the direct properties of a class. The ExtendedReflectiveColumnPropertyAccessor also supports nested properties. It is created the same way, but you specify nested properties with dot separated names.

String[] propertyNames = {"firstName", "lastName", "address.street", "address.city"};

IColumnPropertyAccessor<PersonWithAddress> columnPropertyAccessor =
    new ExtendedReflectiveColumnPropertyAccessor<PersonWithAddress>(propertyNames);

5.7. Calculated values

The default implementations are sufficient for most use cases. Calculated values need a custom implementation. You could extend the model with the calculated value, but for a clean separation it usually is not part of the model.

To add a column with calculated values, create an IColumnAccessor that calculates the value in getDataValue().

class CalculatingDataProvider implements IColumnAccessor<NumberValues> {

    @Override
    public Object getDataValue(NumberValues rowObject, int columnIndex) {
        switch(columnIndex) {
            case 0: return rowObject.getColumnOneNumber();
            case 1: return rowObject.getColumnTwoNumber();
            case 2: return rowObject.getColumnThreeNumber();
            case 3: //calculate the sum
                    return rowObject.getColumnTwoNumber() + rowObject.getColumnThreeNumber();
            case 4: //calculate the percentage
                    return (double) (rowObject.getColumnTwoNumber() + rowObject.getColumnThreeNumber())
                        / rowObject.getColumnOneNumber();
        }
        return null;
    }

    @Override
    public void setDataValue(NumberValues rowObject, int columnIndex, Object newValue) {
        switch(columnIndex) {
            case 0: rowObject.setColumnOneNumber((Integer)newValue);
                    break;
            case 1: rowObject.setColumnTwoNumber((Integer)newValue);
                    break;
            case 2: rowObject.setColumnThreeNumber((Integer)newValue);
                    break;
            //as column 3 and 4 are calculated we don't need to update the model
        }
    }

    @Override
    public int getColumnCount() {
        //this example will show exactly 5 columns
        return 5;
    }
}

The full example can be found in the NatTable Examples Application Tutorial Examples  Data  CalculatedDataExample

The example calculates the value on every request, which can cause performance issues. The CalculatedValueCache avoids this. An example is in the NatTable Examples Application Tutorial Examples  Integration  CachedCalculatingGridExample

5.8. Dynamic columns

The number of columns is typically fixed by the members of a class. For dynamic columns, implement a custom IDataProvider or IColumnPropertyAccessor that accesses column properties dynamically, similar to how the ListDataProvider accesses rows. This works for example if the model contains a collection of values.

You can find an example for dynamic columns in the NatTable Examples Application Tutorial Examples  Data  DynamicColumnExample

6. Install NatTable with a target definition

7. Exercise: Setting up a basic NatTable example

This exercise creates a view that shows your data model in a NatTable, one element per row. You can contribute the view to any Eclipse-based application.

Create a new simple plug-in called com.vogella.nattable via the File  New  Other  Plug-in Development  Plug-in Project menu entry. On the second page of the wizard select the options similar to the following screenshot No template is needed, so press Finish on the second page.

Content page of the New Plug-in Project wizard with the ID com.vogella.nattable

7.1. Configure the dependencies

Open the MANIFEST.MF file and add the following dependencies to the Required Plug-ins in the Dependencies section.

  • com.vogella.tasks.model

  • com.vogella.tasks.services

  • org.eclipse.jface

  • org.eclipse.nebula.widgets.nattable.core

The manifest should look similar to the following listing. Your manifest may contain minimum version constraints, which is fine.

Solution example
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Nattable
Bundle-SymbolicName: com.vogella.nattable;singleton:=true
Bundle-Version: 1.0.0.qualifier
Bundle-Vendor: VOGELLA
Require-Bundle: com.vogella.tasks.model,
 com.vogella.tasks.services,
 org.eclipse.jface,
 org.eclipse.nebula.widgets.nattable.core
Bundle-RequiredExecutionEnvironment: JavaSE-25
Import-Package: jakarta.annotation,
 jakarta.inject
Automatic-Module-Name: com.vogella.nattable

7.2. Update your product

Also add org.eclipse.nebula.widgets.nattable.core.feature to your product. And add com.vogella.nattable to your own feature.

7.3. Validate your setup

Start via your product and ensure that you see no dependency errors for your plug-ins during startup.

7.4. Add a part to your Eclipse IDE

Create a new class called com.vogella.nattable.parts.NattableExample.

Add a new model fragment to your com.vogella.nattable plug-in. Add here a part descriptor to your application, similar to the following screenshots.

Model fragment editor with the model fragment for the descriptors feature selected
Part descriptor details with the label and the Class URI

7.5. Create the NatTable instance

Change the NattableExample class similar to the following listing.

package com.vogella.nattable.parts;

import jakarta.annotation.PostConstruct;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
import org.eclipse.nebula.widgets.nattable.data.ReflectiveColumnPropertyAccessor;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.vogella.tasks.model.Task;
import com.vogella.tasks.model.TaskService;

public class NattableExample {
    
    @PostConstruct
    public void postConstruct(Composite parent, TaskService taskService) {
        parent.setLayout(new GridLayout());

        // property names of the Task class
        String[] propertyNames = { Task.FIELD_ID, Task.FIELD_SUMMARY, Task.FIELD_DESCRIPTION, Task.FIELD_DONE,
                Task.FIELD_DUEDATE };

        // create the data provider
        IColumnPropertyAccessor<Task> columnPropertyAccessor = new ReflectiveColumnPropertyAccessor<>(propertyNames);
        IDataProvider bodyDataProvider = new ListDataProvider<Task>(taskService.getAll(),
                columnPropertyAccessor);

        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);

        // use different style bits to avoid rendering of inactive scrollbars for small
        // table
        // Note: The enabling/disabling and showing of the scrollbars is handled by the
        // ViewportLayer. Without the ViewportLayer the scrollbars will always be
        // visible with the default style bits of NatTable.
        NatTable natTable = new NatTable(parent, SWT.NO_REDRAW_RESIZE | SWT.DOUBLE_BUFFERED | SWT.BORDER,
                bodyDataLayer);

        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
    }
    
    
    
    
}

The example uses the ReflectiveColumnPropertyAccessor that is created using a String array. It is used to create a ListDataProvider together with the list of Task objects that is retrieved from the TaskService.

The layer composition in this example consists only of the DataLayer. It is therefore directly used to create the NatTable instance.

As there is no other layer involved, the created table does not support scrolling. Therefore this example uses style bits to avoid rendering scrollbars that never get active.

7.6. Validate your table implementation

Start the application via the product definition file and Launch an Eclipse application. The part shows your tasks, similar to the following screenshot.

Table without headers showing ten tasks with id, summary, description, done state and due date

If you have problems starting your application, check the dependencies section of your product. It should contain the org.eclipse.nebula.widgets.nattable.core plug-in. Click the Select Required button if it is not included.

You cannot scroll the table yet. The next exercises add this.

7.7. Exercise: Create your custom property accessor

In the previous exercise a ReflectiveColumnPropertyAccessor was used to access the data object properties.

Reflection is not the fastest way of accessing Java objects. To avoid this performance impact a custom IColumnPropertyAccessor<R> will be implemented in this exercise.

7.7.1. Implement a custom IColumnPropertyAccessor for a Person

Create the following class.

package com.vogella.nattable.parts;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor;

import com.vogella.tasks.model.Task;

public class TaskColumnPropertyAccessor implements IColumnPropertyAccessor<Task> {

    // property names of the Task class
    // will also be used for the column header once you define them
    public static final List<String> propertyNames = 
            Arrays.asList(Task.FIELD_ID, Task.FIELD_SUMMARY, Task.FIELD_DESCRIPTION, Task.FIELD_DONE,
                    Task.FIELD_DUEDATE);

    @Override
    public Object getDataValue(Task task, int columnIndex) {
        switch (columnIndex) {
            case 0:
                return task.getId();
            case 1:
                return task.getSummary();
            case 2:
                return task.getDescription();
            case 3:
                return task.isDone();
            case 4:
                return task.getDueDate();
            default:
                return "UNDEFINED";
            }
    }

    @Override
    public void setDataValue(Task task, int columnIndex, Object newValue) {
        switch (columnIndex) {
            case 0:
                throw new IllegalArgumentException("change not allowed");
            case 1:
                task.setSummary(String.valueOf(newValue));
                break;
            case 2:
                task.setDescription(String.valueOf(newValue));
                break;
            case 3:
                task.setDone((boolean) newValue);
                break;
            case 4:
                task.setDueDate(newValue instanceof LocalDate date ? date : LocalDate.parse(String.valueOf(newValue)));
                break;
            default:
                throw new IllegalArgumentException("column number out of range");

        }
    }

    @Override
    public int getColumnCount() {
        return propertyNames.size();
    }

    @Override
    public String getColumnProperty(int columnIndex) {
        return propertyNames.get(columnIndex);
    }

    @Override
    public int getColumnIndex(String propertyName) {
        return propertyNames.indexOf(propertyName);
    }

}

Now use this new class in the NattableExample class.

package com.vogella.nattable.parts;

import jakarta.annotation.PostConstruct;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.vogella.tasks.model.Task;
import com.vogella.tasks.model.TaskService;

public class NattableExample {
    
    @PostConstruct
    public void postConstruct(Composite parent, TaskService taskService) {
        parent.setLayout(new GridLayout());

        IColumnPropertyAccessor<Task> columnPropertyAccessor = new TaskColumnPropertyAccessor();
        IDataProvider bodyDataProvider = new ListDataProvider<Task>(taskService.getAll(),
                columnPropertyAccessor);

        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);

        NatTable natTable = new NatTable(parent, SWT.NO_REDRAW_RESIZE | SWT.DOUBLE_BUFFERED | SWT.BORDER,
                bodyDataLayer);

        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
    }
    
}

7.7.2. Run

When running the application the NatTableDataExamplePart should look completely equal to the one before. But it uses dedicated access to the data model instead of using reflection.

8. Exercise: NatTable column width

In this exercise, you assign widths to the columns in your NatTable. The description column of a person should have more weight and the done column should have a fixed size of 50.

8.1. Adding fixed and percentage values as column widths

The different sizing constraints will be applied to the underlying data layer.

package com.vogella.nattable.parts;

import jakarta.annotation.PostConstruct;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.vogella.tasks.model.Task;
import com.vogella.tasks.model.TaskService;

public class NattableExample {
    
    @PostConstruct
    public void postConstruct(Composite parent, TaskService taskService) {
        parent.setLayout(new GridLayout());

        IColumnPropertyAccessor<Task> columnPropertyAccessor = new TaskColumnPropertyAccessor();
        IDataProvider bodyDataProvider = new ListDataProvider<Task>(taskService.getAll(),
                columnPropertyAccessor);

        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);

        // activate percentage sizing for all columns
        bodyDataLayer.setColumnPercentageSizing(true);

        // Use percentage values for the first three columns column
        bodyDataLayer.setColumnWidthPercentageByPosition(0, 5);
        bodyDataLayer.setColumnWidthPercentageByPosition(1, 30);
        bodyDataLayer.setColumnWidthPercentageByPosition(2, 30);

        // deactivate percentage sizing for the fourth column (isDone)
        bodyDataLayer.setColumnPercentageSizing(3, false);
        // apply a fixed size for the fourth column
        bodyDataLayer.setColumnWidthByPosition(3, 50);

        // also use percentage sizing for the dueDate column
        bodyDataLayer.setColumnWidthPercentageByPosition(4, 35);

        NatTable natTable = new NatTable(parent, SWT.NO_REDRAW_RESIZE | SWT.DOUBLE_BUFFERED | SWT.BORDER,
                bodyDataLayer);

        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
    }
    
    
    
    
}

8.2. Validate

The actual part should look like this:

Table whose columns share the available width

Try to shrink the window and see how the percentage column sizing working.

The same table in a narrower window

Ensure that the done column keeps its fixed size.

9. Overview of the NatTable layers

A NatTable is built from layers that can be stacked and composed. Every layer has its own functionality and encapsulates cell transformations if necessary.

The following layers ship with NatTable.

Table 4. NatTable Layers
Layer Description

DataLayer

Provides the data that is shown in a layer stack.

ViewportLayer

Adds the virtual nature to a NatTable instance.

SelectionLayer

Adds the ability to perform selection actions.

HoverLayer

Adds the ability to change styling on hover.

ColumnHideShowLayer

Adds the ability to hide columns.

RowHideShowLayer

Adds the ability to hide rows.

GlazedListsRowHideShowLayer

Adds the ability to hide rows when the data model collection is wrapped by GlazedLists.

ColumnReorderLayer

Adds the ability to reorder columns.

RowReorderLayer

Adds the ability to reorder rows.

SortHeaderLayer

Adds the ability to sort columns by clicking on the column header.

FilterRowHeaderComposite

Adds a filter row between the column header and the body of a NatTable composition.

ColumnGroupHeaderLayer

Adds a second level column header to group columns.

ColumnGroupGroupHeaderLayer

Adds a third level column header to group columns and column groups.

ColumnGroupReorderLayer

Adds the ability to reorder column groups.

ColumnGroupExpandCollapseLayer

Adds the ability to expand and collapse column groups.

RowGroupHeaderLayer

Adds a second level row header to group rows.

SummaryRowLayer

Adds a summary row at the end of a NatTable instance.

FreezeLayer

Handles and stores states dependent on freezing columns and rows.

CompositeFreezeLayer

Composition to add freeze functionality.

TreeLayer

Transformation layer that shows the underlying data model collection in a tree representation.

BlinkLayer

Adds the ability to dynamically react on data model changes in the background.

GlazedListsEventLayer

Transforms list change events sent by GlazedLists into NatTable events to refresh rendering on list changes. GlazedLists events are conflated in a 100ms interval to reduce the amount of NatTable refresh events.

DetailGlazedListsEventLayer

Transforms list change events sent by GlazedLists into NatTable events to refresh rendering on list changes. Every GlazedLists event is transformed and fired to the NatTable layer stack, transporting the detail information about the list change, e.g., which rows have been deleted.

GroupByHeaderLayer

Adds a section on top where columns can be dragged to dynamically group the data model elements.

GroupByDataLayer

Specialized DataLayer that needs to be used to make the groupBy feature work.

Further layers create composites, most importantly the CompositeLayer, GridLayer, RowHeaderLayer, ColumnHeaderLayer and CornerLayer. The following chapters explain them.

10. Exercise: Implementing a layer stack

This exercise makes the table scrollable and selectable with a basic layer stack.

10.1. Create the NatTable instance

Change NattableExample to create a layer stack of DataLayer, SelectionLayer and ViewportLayer. Pass the prior layer as the underlyingLayer constructor parameter, as shown below.

DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
SelectionLayer selectionLayer = new SelectionLayer(bodyDataLayer);
ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);

The default UI bindings for selection actions are bound to the GridRegion.BODY region label. As there is no grid composition yet, set the region label manually.

viewportLayer.setRegionName(GridRegion.BODY);

Use the viewportLayer in the new NatTable call.

It is not necessary to set custom style bits, as now a ViewportLayer is used, which handles the scrollbars automatically.

package com.vogella.nattable.parts;

import jakarta.annotation.PostConstruct;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
import org.eclipse.nebula.widgets.nattable.selection.config.DefaultRowSelectionLayerConfiguration;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.vogella.tasks.model.Task;
import com.vogella.tasks.model.TaskService;

public class NattableExample {
    
    @PostConstruct
    public void postConstruct(Composite parent, TaskService taskService) {
        parent.setLayout(new GridLayout());

        IColumnPropertyAccessor<Task> columnPropertyAccessor = new TaskColumnPropertyAccessor();
        IDataProvider bodyDataProvider = new ListDataProvider<Task>(taskService.getAll(),
                columnPropertyAccessor);

        // create layer stack consisting out of:
        // data layer
        // selection layer
        // viewport layer
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
        setColumnWidth(bodyDataLayer);

        // selection layer
        SelectionLayer selectionLayer = new SelectionLayer(bodyDataLayer);
        // Enable full selection for rows
        selectionLayer.addConfiguration(new DefaultRowSelectionLayerConfiguration());


        // view port layer
        ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);

        // as the selection mouse bindings are registered for the region label
        // GridRegion.BODY
        // we need to set that region label to the viewport so the selection via mouse
        // is working correctly
        viewportLayer.setRegionName(GridRegion.BODY);


        NatTable natTable = new NatTable(parent, viewportLayer);

        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
    }

    private void setColumnWidth(DataLayer bodyDataLayer) {
        // activate percentage sizing for all columns
        bodyDataLayer.setColumnPercentageSizing(true);

        // Use percentage values for the first three columns column
        bodyDataLayer.setColumnWidthPercentageByPosition(0, 5);
        bodyDataLayer.setColumnWidthPercentageByPosition(1, 30);
        bodyDataLayer.setColumnWidthPercentageByPosition(2, 40);

        // deactivate percentage sizing for the fourth column (isDone)
        bodyDataLayer.setColumnPercentageSizing(3, false);
        // apply a fixed size for the fourth column
        bodyDataLayer.setColumnWidthByPosition(3, 50);

        // also use percentage sizing for the dueDate column
        bodyDataLayer.setColumnWidthPercentageByPosition(4, 25);
    }
    
    
    
    
}

10.2. Run

Start your application and show the view. The table is now scrollable and supports selection.

Scrollable table without headers showing tasks

11. Layer compositions

Additionally to stacking up layers, it is possible to create compositions and arrange layer stacks side by side. Following the design principles in NatTable, this is achieved by using a CompositeLayer. A CompositeLayer is itself column and row based, where every part is called a region. To create a CompositeLayer you need to specify the number of columns and rows of regions. Afterwards, the layers/layer stacks can be put in the CompositeLayer by calling CompositeLayer#setChildLayer(String, ILayer, int, int), where the first parameter specifies the region label.

// create a composition with one column and two rows
CompositeLayer compositeLayer = new CompositeLayer(1, 2);
// set the column header layer in the first row of the first column
compositeLayer.setChildLayer(GridRegion.COLUMN_HEADER, columnHeaderLayer, 0, 0);
// set the viewport layer in the second row of the first column
compositeLayer.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);

11.1. Dimensional dependencies

In a layer composition typically one region is leading in terms of cell boundaries. For example, in a composition that contains a body and a column header, the body is typically scrollable, so the column header cell boundaries need to follow the cell boundaries of the body cells.

Layers whose cell boundaries are attached to the cell boundaries of another layer are called dimensionally dependent. Every dimensionally dependent layer extends DimensionallyDependentLayer and needs to know the layer it depends on at creation time.

Layers can either be horizontally dependent (e.g., ColumnHeaderLayer), vertically dependent (e.g., RowHeaderLayer) or both horizontally and vertically dependent (e.g., CornerLayer).

11.2. Creating a grid composition

The GridLayer is a specialized CompositeLayer that has two rows and two columns. It therefore has four regions:

  • Corner (upper left region)

  • Column Header (upper right region)

  • Row Header (bottom left region)

  • Body (bottom right region)

11.3. GridLayer default configuration

The GridLayer has default configurations for the grid behavior, aggregated in DefaultGridLayerConfiguration.

Table 5. Default configurations
Configuration class Description

DefaultExportBindings

Adds the key binding for exporting a NatTable and configuration regarding the default export settings.

DefaultPrintBindings

Adds the key binding for printing a NatTable.

DefaultEditBindings

Adds the UI bindings for keys and mouse interactions regarding the editing behavior.

DefaultEditConfiguration

Registers the command handlers necessary for editing and adds default configurations like the default cell editor, the editable rule and the default data validator.

DefaultRowStyleConfiguration

Configures the styling for alternating row colors.

If a function does not work in a custom layer composition, check that the necessary default configurations are added to your CompositeLayer.

11.4. GridLayer commands

The following commands are handled by the GridLayer.

Table 6. Commands
Command CommandHandler Description

ClientAreaResizeCommand

GridLayer

Performs additional transformations to correctly support percentage sizing.

PrintCommand

PrintCommandHandler

Prints the NatTable.

ExportCommand

ExportCommandHandler

Exports the NatTable to an Excel compatible format.

AutoResizeColumnsCommand

AutoResizeColumnCommandHandler

Performs an auto resize for a specified column.

AutoResizeRowsCommand

AutoResizeRowCommandHandler

Performs an auto resize for a specified row.

11.5. Layer stack of the body region

The body layer stack is the main part of a NatTable composition. It typically handles selection and the virtual nature via the viewport, plus layers for features like column reordering or hiding.

// build the body layer stack
IDataProvider bodyDataProvider
    = new ListDataProvider<Task>(taskService.getAll(), columnPropertyAccessor);
DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
SelectionLayer selectionLayer = new SelectionLayer(bodyDataLayer);
ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);

11.6. Layer stack of the column header region

The column header layer stack renders the column header and has a horizontal dimensional dependency to the body layer stack, which the ColumnHeaderLayer resolves.

A ColumnHeaderLayer needs three layers:

  • the underlying base layer, typically the DataLayer of the column header region

  • the layer that resolves the dimensional dependency, typically the ViewportLayer or a custom body layer stack

  • the SelectionLayer, to show the selection in the column header

You can add further layers to the stack. The SortHeaderLayer sorts the content via a click on the column header cells, and the ColumnGroupHeaderLayer adds a row on top of the column header for grouping columns.

The IDataProvider of the column header layer stack must have the same number of columns as the IDataProvider of the body layer stack. Otherwise, setting up the horizontal dependency fails at runtime.

// build the column header layer stack
IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(propertyNames, propertyToLabelMap);
DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
ILayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer,  selectionLayer);

11.7. Layer stack of the row header region

The row header layer stack renders the row header and has a vertical dimensional dependency to the body layer stack, which the RowHeaderLayer resolves. A RowHeaderLayer needs the underlying base layer (typically the DataLayer of the row header region), the layer that resolves the dimensional dependency, and the SelectionLayer to show the selection in the row header.

The DefaultRowHeaderDataProvider ties the number of rows to the body layer stack and returns row index + 1 as content. Use a different IDataProvider to show other information.

The IDataProvider of the row header layer stack must have the same number of rows as the IDataProvider of the body layer stack. Otherwise, setting up the vertical dependency fails at runtime.

You can add further layers to the stack. The RowGroupHeaderLayer, for example, adds a column to the left of the row header for grouping rows.

// build the row header layer stack
IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
DataLayer rowHeaderDataLayer = new DataLayer(rowHeaderDataProvider, 40, 20);
ILayer rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, viewportLayer, selectionLayer);

11.8. Layer stack of the corner region

The corner layer stack is typically non functional and fills the fourth region of the grid. It is dimensionally dependent on both the column header region and the row header region.

// build the corner layer stack
IDataProvider cornerDataProvider =  new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider);
DataLayer cornerDataLayer = new DataLayer(cornerDataProvider);
ILayer cornerLayer = new CornerLayer(cornerDataLayer, rowHeaderLayer,  columnHeaderLayer);

You can add content or other layers to the corner layer stack.

12. Exercise: NatTable Layer Composition

This exercise composes a column header and the body in one NatTable.

12.1. Add data and data provider for the column headers

To display table headers, you need:

  • data for the columns

  • a data provider for the columns

Create a map from property names to column labels.

Map<String, String> propertyToLabelMap = Map.of("id", "ID", "summary", "Summary", "description",
    "Description", "done", "Done", "dueDate", "Due Date");

Use the default DefaultColumnHeaderDataProvider as data provider of the column header region and build a column header layer stack of DataLayer and ColumnHeaderLayer.

// build the column header layer stack
IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
    TaskColumnPropertyAccessor.propertyNames.toArray(new String[0]), propertyToLabelMap);
DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
ILayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);

There are two ways to create a DefaultColumnHeaderDataProvider. Either specify a String array with the same size as the column specification, where every entry is the label for the column at the specified index. Or create a Map that contains a mapping from property name to label and provide it as parameter together with the String array of property names that was already used to create the ReflectiveColumnPropertyAccessor.

Create a CompositeLayer and set the column header layer stack and the body layer stack to the appropriate positions. The following code snippet gives an example on how this should look like.

// create a composition with one column and two rows
CompositeLayer compositeLayer = new CompositeLayer(1, 2);
// set the column header layer in the first row of the first column
compositeLayer.setChildLayer(GridRegion.COLUMN_HEADER, columnHeaderLayer, 0, 0);
// set the viewport layer in the second row of the first column
compositeLayer.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);

Create a NatTable instance for the created CompositeLayer that uses the compositeLayer layer configurations.

package com.vogella.nattable.parts;

import java.util.Map;

import jakarta.annotation.PostConstruct;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
import org.eclipse.nebula.widgets.nattable.layer.CompositeLayer;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
import org.eclipse.nebula.widgets.nattable.selection.config.DefaultRowSelectionLayerConfiguration;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.vogella.tasks.model.Task;
import com.vogella.tasks.model.TaskService;

public class NattableExample {
    
    Map<String, String> propertyToLabelMap = Map.of("id", "ID", "summary", "Summary", "description", "Description",
            "done", "Done", "dueDate", "Due Date");

    @PostConstruct
    public void postConstruct(Composite parent, TaskService taskService) {
        parent.setLayout(new GridLayout());

        IColumnPropertyAccessor<Task> columnPropertyAccessor = new TaskColumnPropertyAccessor();
        IDataProvider bodyDataProvider = new ListDataProvider<Task>(taskService.getAll(),
                columnPropertyAccessor);

        // create the body layer stack consisting out of:
        // data layer
        // selection layer
        // viewport layer
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
        setColumnWidth(bodyDataLayer);

        // selection layer
        SelectionLayer selectionLayer = new SelectionLayer(bodyDataLayer);
        // Enable full selection for rows
        selectionLayer.addConfiguration(new DefaultRowSelectionLayerConfiguration());


        // view port layer
        ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);

        // as the selection mouse bindings are registered for the region label
        // GridRegion.BODY
        // we need to set that region label to the viewport so the selection via mouse
        // is working correctly
        viewportLayer.setRegionName(GridRegion.BODY);

        // create the column header layer stack
        IDataProvider headerDataProvider = new DefaultColumnHeaderDataProvider(
                TaskColumnPropertyAccessor.propertyNames.toArray(new String[0]),
                propertyToLabelMap);
        DataLayer headerDataLayer = new DataLayer(headerDataProvider);
        ILayer columnHeaderLayer = new ColumnHeaderLayer(headerDataLayer, viewportLayer, selectionLayer);

        // create a composition with one column and two rows
        CompositeLayer compositeLayer = new CompositeLayer(1, 2);
        // set the column header layer in the first row of the first column
        // set the region labels to make default configurations work, e.g., selection
        compositeLayer.setChildLayer(GridRegion.COLUMN_HEADER, columnHeaderLayer, 0, 0);
        // set the viewport layer in the second row of the first column
        compositeLayer.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);

        NatTable natTable = new NatTable(parent, compositeLayer);

        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
    }

    private void setColumnWidth(DataLayer bodyDataLayer) {
        // activate percentage sizing for all columns
        bodyDataLayer.setColumnPercentageSizing(true);

        // Use percentage values for the first three columns column
        bodyDataLayer.setColumnWidthPercentageByPosition(0, 5);
        bodyDataLayer.setColumnWidthPercentageByPosition(1, 30);
        bodyDataLayer.setColumnWidthPercentageByPosition(2, 40);

        // deactivate percentage sizing for the fourth column (isDone)
        bodyDataLayer.setColumnPercentageSizing(3, false);
        // apply a fixed size for the fourth column
        bodyDataLayer.setColumnWidthByPosition(3, 50);

        // also use percentage sizing for the dueDate column
        bodyDataLayer.setColumnWidthPercentageByPosition(4, 25);
    }
    
    
    
    
}

12.2. Run

Start your application and open the view. The view shows the scrollable composition of column header and body.

Table with a column header showing tasks

13. Exercise: NatTable grid

This exercise builds a grid layer composition with:

  • a body

  • a column header

  • a row header

  • a corner

13.1. Prepare the stacks for the grid composition

The column header layer stack of DataLayer and ColumnHeaderLayer exists already. Build a row header layer stack of DataLayer and RowHeaderLayer, similar to the following snippet.

// build the row header layer stack
IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
DataLayer rowHeaderDataLayer = new DataLayer(rowHeaderDataProvider, 40, 20);
ILayer rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, viewportLayer, selectionLayer);

Build a corner layer stack of DataLayer and CornerLayer, similar to the following snippet.

// build the corner layer stack
IDataProvider cornerDataProvider =  new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider);
DataLayer cornerDataLayer = new DataLayer(cornerDataProvider);
ILayer cornerLayer = new CornerLayer(cornerDataLayer, rowHeaderLayer,  columnHeaderLayer);

13.2. Build your grid with the created stacks

Build up a GridLayer using the prior created layer stacks in the correct positions, similar to the following code snippet.

// create the grid layer composed with the prior created layer stacks
GridLayer gridLayer = new GridLayer(viewportLayer, columnHeaderLayer, rowHeaderLayer, cornerLayer);

Create a NatTable instance for the created GridLayer that uses the default configurations.

package com.vogella.nattable.parts;

import java.util.Map;

import jakarta.annotation.PostConstruct;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.RowHeaderLayer;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
import org.eclipse.nebula.widgets.nattable.selection.config.DefaultRowSelectionLayerConfiguration;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.vogella.tasks.model.Task;
import com.vogella.tasks.model.TaskService;

public class NattableExample {

    Map<String, String> propertyToLabelMap = Map.of("id", "ID", "summary", "Summary", "description", "Description",
            "done", "Done", "dueDate", "Due Date");

    @PostConstruct
    public void postConstruct(Composite parent, TaskService taskService) {
        parent.setLayout(new GridLayout());

        // build the body layer stack
        IColumnPropertyAccessor<Task> columnPropertyAccessor = new TaskColumnPropertyAccessor();
        IDataProvider bodyDataProvider = new ListDataProvider<>(taskService.getAll(), columnPropertyAccessor);
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
        setColumnWidth(bodyDataLayer);
        SelectionLayer selectionLayer = new SelectionLayer(bodyDataLayer);
        selectionLayer.addConfiguration(new DefaultRowSelectionLayerConfiguration());
        ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);
        viewportLayer.setRegionName(GridRegion.BODY);

        // build the column header layer stack
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
                TaskColumnPropertyAccessor.propertyNames.toArray(new String[0]), propertyToLabelMap);
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
        ILayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);

        // build the row header layer stack
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
        DataLayer rowHeaderDataLayer = new DataLayer(rowHeaderDataProvider, 40, 20);
        ILayer rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, viewportLayer, selectionLayer);

        // build the corner layer stack
        IDataProvider cornerDataProvider = new DefaultCornerDataProvider(columnHeaderDataProvider,
                rowHeaderDataProvider);
        ILayer cornerLayer = new CornerLayer(new DataLayer(cornerDataProvider), rowHeaderLayer, columnHeaderLayer);

        // create the grid layer composed with the prior created layer stacks
        GridLayer gridLayer = new GridLayer(viewportLayer, columnHeaderLayer, rowHeaderLayer, cornerLayer);

        NatTable natTable = new NatTable(parent, gridLayer);

        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
    }

    private void setColumnWidth(DataLayer bodyDataLayer) {
        bodyDataLayer.setColumnPercentageSizing(true);
        bodyDataLayer.setColumnWidthPercentageByPosition(0, 5);
        bodyDataLayer.setColumnWidthPercentageByPosition(1, 30);
        bodyDataLayer.setColumnWidthPercentageByPosition(2, 40);
        bodyDataLayer.setColumnPercentageSizing(3, false);
        bodyDataLayer.setColumnWidthByPosition(3, 50);
        bodyDataLayer.setColumnWidthPercentageByPosition(4, 25);
    }

}

13.3. Run

Start the example application and open your view.

In a grid the headers typically do not move while scrolling the body region. And because of the default configuration of the GridLayer it is possible to print Ctrl+P and export Ctrl+E the NatTable instance.

Grid with column header and row header showing tasks

14. Exercise: Adding a sort functionality to a NatTable

In this exercise a click on a column header sorts the rows according to the values of this column. You will:

  • use a SortedList (GlazedLists) for the IDataProvider

  • wrap ColumnHeaderLayer in a SortHeaderLayer

  • add SingleClickSortConfiguration as UI Binding

14.1. Creating a part with a NatTable

Change your view to allow sorting based on columns. For this, you have to create your IDataProvider with a sortable list from the GlazedList framework. Also you have to create an explicit ConfigRegistry as the sort layer needs one.

ConfigRegistry configRegistry = new ConfigRegistry();
EventList<Task> tasks = GlazedLists.eventList(taskService.getAll());
SortedList<Task> sortedList = new SortedList<>(tasks, null);

IColumnPropertyAccessor<Task> accessor = new TaskColumnPropertyAccessor();
IDataProvider bodyDataProvider = new ListDataProvider<Task>(sortedList, accessor);

Afterwards, you have to create a SortHeaderLayer for your column header layer.

SortHeaderLayer<Task> sortHeaderLayer = new SortHeaderLayer<>(columnHeaderLayer,
                new GlazedListsSortModel<>(sortedList, accessor, configRegistry, columnHeaderDataLayer));

And of course, you have to use this new layer instead of the columnHeaderLayer in your Nattable configuration and configure it.

// create the grid layer composed with the prior created layer stacks
GridLayer gridLayer = new GridLayer(viewportLayer, sortHeaderLayer, rowHeaderLayer, cornerLayer);

NatTable natTable = new NatTable(parent, gridLayer, false);
natTable.setConfigRegistry(configRegistry);
natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
natTable.addConfiguration(new SingleClickSortConfiguration());
natTable.configure();
package com.vogella.nattable.parts;


import java.util.Map;

import jakarta.annotation.PostConstruct;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsSortModel;
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.RowHeaderLayer;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
import org.eclipse.nebula.widgets.nattable.selection.config.DefaultRowSelectionLayerConfiguration;
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.vogella.tasks.model.Task;
import com.vogella.tasks.model.TaskService;

import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.SortedList;

public class NattableExample {
    
    Map<String, String> propertyToLabelMap = Map.of("id", "ID", "summary", "Summary", "description", "Description",
            "done", "Done", "dueDate", "Due Date");

    @PostConstruct
    public void postConstruct(Composite parent, TaskService taskService) {
        parent.setLayout(new GridLayout());

        ConfigRegistry configRegistry = new ConfigRegistry();

        EventList<Task> tasks = GlazedLists.eventList(taskService.getAll());
        SortedList<Task> sortedList = new SortedList<>(tasks, null);

        IColumnPropertyAccessor<Task> accessor = new TaskColumnPropertyAccessor();
        IDataProvider bodyDataProvider = new ListDataProvider<Task>(sortedList,
                accessor);

        // create the body layer stack consisting out of:
        // data layer
        // selection layer
        // viewport layer
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
        setColumnWidth(bodyDataLayer);

        // selection layer
        SelectionLayer selectionLayer = new SelectionLayer(bodyDataLayer);
        // Enable full selection for rows
        selectionLayer.addConfiguration(new DefaultRowSelectionLayerConfiguration());


        // view port layer
        ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);

        // as the selection mouse bindings are registered for the region label
        // GridRegion.BODY
        // we need to set that region label to the viewport so the selection via mouse
        // is working correctly
        viewportLayer.setRegionName(GridRegion.BODY);

        // create the column header layer stack
        // build the column header layer stack
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
                TaskColumnPropertyAccessor.propertyNames.toArray(new String[0]), propertyToLabelMap);
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
        ILayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);
        
        SortHeaderLayer<Task> sortHeaderLayer = new SortHeaderLayer<>(columnHeaderLayer,
                new GlazedListsSortModel<>(sortedList, accessor, configRegistry, columnHeaderDataLayer));

        // create the row the row header layer stack
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
        DataLayer rowHeaderDataLayer = new DataLayer(rowHeaderDataProvider, 40, 20);
        ILayer rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, viewportLayer, selectionLayer);

        // build the corner layer stack
        IDataProvider cornerDataProvider =  new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider);
        DataLayer cornerDataLayer = new DataLayer(cornerDataProvider);
        ILayer cornerLayer = new CornerLayer(cornerDataLayer, rowHeaderLayer, columnHeaderLayer);


        // create the grid layer composed with the prior created layer stacks
        GridLayer gridLayer = new GridLayer(viewportLayer, sortHeaderLayer, rowHeaderLayer, cornerLayer);


        NatTable natTable = new NatTable(parent, gridLayer, false);
        natTable.setConfigRegistry(configRegistry);
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
        natTable.addConfiguration(new SingleClickSortConfiguration());
        natTable.configure();

        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
    }

    private void setColumnWidth(DataLayer bodyDataLayer) {
        // activate percentage sizing for all columns
        bodyDataLayer.setColumnPercentageSizing(true);

        // Use percentage values for the first three columns column
        bodyDataLayer.setColumnWidthPercentageByPosition(0, 5);
        bodyDataLayer.setColumnWidthPercentageByPosition(1, 30);
        bodyDataLayer.setColumnWidthPercentageByPosition(2, 40);

        // deactivate percentage sizing for the fourth column (isDone)
        bodyDataLayer.setColumnPercentageSizing(3, false);
        // apply a fixed size for the fourth column
        bodyDataLayer.setColumnWidthByPosition(3, 50);

        // also use percentage sizing for the dueDate column
        bodyDataLayer.setColumnWidthPercentageByPosition(4, 25);
    }
    
}

14.2. Validate

Run the application and click on the header of the Due Date column. The rows are sorted by this column and the header shows a sort indicator. A second click reverses the order and a third click removes the sorting again. Hold the Alt key while clicking on another header to sort by several columns.

Task table sorted by the Due Date column with a sort indicator in the column header

15. Exercise: Adding a filter row to a NatTable

In this exercise the column header gets a filter row, in which the user can type a filter for each column. You will:

  • use a FilterList (GlazedLists) for the IDataProvider

  • wrap the sortable column header in a FilterRowHeaderComposite

  • configure the editors and the matching mode of the filter row cells

15.1. Creating a part with a NatTable

Start from the sorting exercise and put a FilterList on top of the SortedList, so that the data is sorted first and the sorted rows are filtered afterwards. The FilterRowHeaderComposite is created with a filter strategy. The DefaultGlazedListsFilterStrategy applies the text of the filter row cells to the FilterList.

The filter row cells are edited with cell editors. Therefore, the DefaultEditConfiguration must be added to the grid layer and a ConfigRegistry must be shared between the strategy and the NatTable instance.

The FilterRowConfiguration registers config attributes for the filter row cells of a column. The cells are addressed via the label FilterRowDataLayer.FILTER_ROW_COLUMN_LABEL_PREFIX plus the column position. Some config attributes for the FilterRowHeaderComposite are:

  • EditConfigAttributes.CELL_EDITOR to define how the filter value is entered

  • FilterRowConfigAttributes.TEXT_MATCHING_MODE to define how the text is compared with the cell value

  • CellConfigAttributes.DISPLAY_CONVERTER to convert between the filter text and the filter expression

The FilterRowConfiguration for this exercise should look like this:

package com.vogella.nattable.parts;

import java.util.Arrays;

import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration;
import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes;
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes;
import org.eclipse.nebula.widgets.nattable.edit.editor.ComboBoxCellEditor;
import org.eclipse.nebula.widgets.nattable.filterrow.FilterRowDataLayer;
import org.eclipse.nebula.widgets.nattable.filterrow.FilterRowRegularExpressionConverter;
import org.eclipse.nebula.widgets.nattable.filterrow.FilterRowTextCellEditor;
import org.eclipse.nebula.widgets.nattable.filterrow.TextMatchingMode;
import org.eclipse.nebula.widgets.nattable.filterrow.config.FilterRowConfigAttributes;
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;

public class FilterRowConfiguration extends AbstractRegistryConfiguration {

    private static final String SUMMARY_FILTER = FilterRowDataLayer.FILTER_ROW_COLUMN_LABEL_PREFIX + 1;
    private static final String DONE_FILTER = FilterRowDataLayer.FILTER_ROW_COLUMN_LABEL_PREFIX + 3;

    @Override
    public void configureRegistry(IConfigRegistry configRegistry) {

        // the summary column filters with regular expressions while typing
        configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new FilterRowTextCellEditor(),
                DisplayMode.NORMAL, SUMMARY_FILTER);
        configRegistry.registerConfigAttribute(FilterRowConfigAttributes.TEXT_MATCHING_MODE,
                TextMatchingMode.REGULAR_EXPRESSION, DisplayMode.NORMAL, SUMMARY_FILTER);
        configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER,
                new FilterRowRegularExpressionConverter(), DisplayMode.NORMAL, SUMMARY_FILTER);

        // the done column offers a combo box with the two possible values
        configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR,
                new ComboBoxCellEditor(Arrays.asList(Boolean.TRUE, Boolean.FALSE)), DisplayMode.NORMAL, DONE_FILTER);
        configRegistry.registerConfigAttribute(FilterRowConfigAttributes.TEXT_MATCHING_MODE, TextMatchingMode.EXACT,
                DisplayMode.NORMAL, DONE_FILTER);

        // several filter expressions in one cell are combined with "&"
        configRegistry.registerConfigAttribute(FilterRowConfigAttributes.TEXT_DELIMITER, "&");
    }
}

The complete code of the NattableExample class would look like this:

package com.vogella.nattable.parts;

import java.util.Map;

import jakarta.annotation.PostConstruct;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
import org.eclipse.nebula.widgets.nattable.edit.config.DefaultEditConfiguration;
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsSortModel;
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.filterrow.DefaultGlazedListsFilterStrategy;
import org.eclipse.nebula.widgets.nattable.filterrow.FilterRowHeaderComposite;
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultColumnHeaderDataLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.RowHeaderLayer;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
import org.eclipse.nebula.widgets.nattable.selection.config.DefaultRowSelectionLayerConfiguration;
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.vogella.tasks.model.Task;
import com.vogella.tasks.model.TaskService;

import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.FilterList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.SortedList;

public class NattableExample {

    Map<String, String> propertyToLabelMap = Map.of("id", "ID", "summary", "Summary", "description", "Description",
            "done", "Done", "dueDate", "Due Date");

    @PostConstruct
    public void postConstruct(Composite parent, TaskService taskService) {
        parent.setLayout(new GridLayout());

        ConfigRegistry configRegistry = new ConfigRegistry();

        // the data is sorted first and the sorted list is filtered afterwards
        EventList<Task> tasks = GlazedLists.threadSafeList(GlazedLists.eventList(taskService.getAll()));
        SortedList<Task> sortedList = new SortedList<>(tasks, null);
        FilterList<Task> filterList = new FilterList<>(sortedList);

        // build the body layer stack
        IColumnPropertyAccessor<Task> accessor = new TaskColumnPropertyAccessor();
        IDataProvider bodyDataProvider = new ListDataProvider<>(filterList, accessor);
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
        setColumnWidth(bodyDataLayer);
        SelectionLayer selectionLayer = new SelectionLayer(bodyDataLayer);
        selectionLayer.addConfiguration(new DefaultRowSelectionLayerConfiguration());
        ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);
        viewportLayer.setRegionName(GridRegion.BODY);

        // build the column header layer stack with sorting and the filter row
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
                TaskColumnPropertyAccessor.propertyNames.toArray(new String[0]), propertyToLabelMap);
        DataLayer columnHeaderDataLayer = new DefaultColumnHeaderDataLayer(columnHeaderDataProvider);
        ILayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);
        SortHeaderLayer<Task> sortHeaderLayer = new SortHeaderLayer<>(columnHeaderLayer,
                new GlazedListsSortModel<>(sortedList, accessor, configRegistry, columnHeaderDataLayer));
        FilterRowHeaderComposite<Task> filterRowHeaderLayer = new FilterRowHeaderComposite<>(
                new DefaultGlazedListsFilterStrategy<>(filterList, accessor, configRegistry), sortHeaderLayer,
                columnHeaderDataProvider, configRegistry);

        // build the row header and the corner layer stack
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
        DataLayer rowHeaderDataLayer = new DataLayer(rowHeaderDataProvider, 40, 20);
        ILayer rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, viewportLayer, selectionLayer);
        ILayer cornerLayer = new CornerLayer(
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
                rowHeaderLayer, filterRowHeaderLayer);

        GridLayer gridLayer = new GridLayer(viewportLayer, filterRowHeaderLayer, rowHeaderLayer, cornerLayer);
        // necessary for the usage of editors, e.g., in the filter row
        gridLayer.addConfiguration(new DefaultEditConfiguration());

        NatTable natTable = new NatTable(parent, gridLayer, false);
        natTable.setConfigRegistry(configRegistry);
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
        natTable.addConfiguration(new SingleClickSortConfiguration());
        natTable.addConfiguration(new FilterRowConfiguration());
        natTable.configure();

        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
    }

    private void setColumnWidth(DataLayer bodyDataLayer) {
        bodyDataLayer.setColumnPercentageSizing(true);
        bodyDataLayer.setColumnWidthPercentageByPosition(0, 8);
        bodyDataLayer.setColumnWidthPercentageByPosition(1, 30);
        bodyDataLayer.setColumnWidthPercentageByPosition(2, 38);
        bodyDataLayer.setColumnPercentageSizing(3, false);
        bodyDataLayer.setColumnWidthByPosition(3, 70);
        bodyDataLayer.setColumnWidthPercentageByPosition(4, 24);
    }
}

15.2. Validate

When running the application the filter row is shown below the column header. Type (Fix|Test).* into the filter cell of the Summary column. The summary column uses regular expressions, so the table shows only the tasks that start with Fix or Test. Select true in the combo box of the Done column to show only the finished tasks of them.

Filter row below the column header with the regular expression (Fix|Test).* in the Summary column

16. Exercise: A NatTable with all the good stuff

In this exercise you combine what you learned and add more features to build a table that shows 100,000 tasks. The table supports sorting, a filter row, column groups, frozen columns, column reordering and hiding, cell editing and switching between several themes.

16.1. Large data sets

NatTable paints only the cells that are visible, so the number of rows hardly matters for the speed of scrolling. The part generates 100,000 tasks and puts them into a GlazedLists EventList. Sorting and filtering are applied by the SortedList and the FilterList that you already know from the previous exercises.

16.2. The layer stack

The following table lists the layers that are new compared to the grid exercise.

Table 7. New layers in this exercise
Layer Purpose

ColumnGroupBodyLayerStack

Convenience body stack with ColumnReorderLayer, ColumnHideShowLayer, SelectionLayer and ViewportLayer that is aware of column groups.

FreezeLayer and CompositeFreezeLayer

Keep the first columns visible while the table scrolls horizontally.

ColumnGroupHeaderLayer

Adds a header row with the groups Task and Status above the column headers.

GlazedListsEventLayer

Updates the table when the underlying list changes, for example after an edit or a filter.

The FilterRowHeaderComposite wraps the ColumnGroupHeaderLayer, which wraps the SortHeaderLayer, so that the grid header consists of the group row, the column header row and the filter row.

16.3. Themes

NatTable ships with the DefaultNatTableThemeConfiguration, the ModernNatTableThemeConfiguration and the DarkNatTableThemeConfiguration. A theme is applied with NatTable#setTheme(ThemeConfiguration) after the table was configured, and it can be exchanged at runtime. The colors of a theme are public fields, so the example derives two small subclasses that add zebra rows and a color scheme that looks the same on every platform.

16.4. Editing

The TaskEditConfiguration makes all cells editable except the ID, paints a checkbox in the Done column and registers a CheckBoxCellEditor and a TextCellEditor. A double-click on a cell or pressing F2 starts the editor. Enter the due date in the format yyyy-MM-dd.

16.5. Create the part

Create the following class. It reuses the TaskColumnPropertyAccessor and the FilterRowConfiguration from the previous exercises.

package com.vogella.nattable.parts;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import jakarta.annotation.PostConstruct;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration;
import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes;
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
import org.eclipse.nebula.widgets.nattable.config.IEditableRule;
import org.eclipse.nebula.widgets.nattable.data.IColumnPropertyAccessor;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
import org.eclipse.nebula.widgets.nattable.data.convert.DefaultBooleanDisplayConverter;
import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes;
import org.eclipse.nebula.widgets.nattable.edit.config.DefaultEditConfiguration;
import org.eclipse.nebula.widgets.nattable.edit.editor.CheckBoxCellEditor;
import org.eclipse.nebula.widgets.nattable.edit.editor.TextCellEditor;
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsEventLayer;
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsSortModel;
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.filterrow.DefaultGlazedListsFilterStrategy;
import org.eclipse.nebula.widgets.nattable.filterrow.FilterRowHeaderComposite;
import org.eclipse.nebula.widgets.nattable.freeze.CompositeFreezeLayer;
import org.eclipse.nebula.widgets.nattable.freeze.FreezeLayer;
import org.eclipse.nebula.widgets.nattable.freeze.command.FreezeColumnCommand;
import org.eclipse.nebula.widgets.nattable.freeze.config.DefaultFreezeGridBindings;
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultColumnHeaderDataLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.RowHeaderLayer;
import org.eclipse.nebula.widgets.nattable.group.ColumnGroupHeaderLayer;
import org.eclipse.nebula.widgets.nattable.group.ColumnGroupModel;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnLabelAccumulator;
import org.eclipse.nebula.widgets.nattable.layer.stack.ColumnGroupBodyLayerStack;
import org.eclipse.nebula.widgets.nattable.painter.cell.CheckBoxPainter;
import org.eclipse.nebula.widgets.nattable.selection.config.DefaultRowSelectionLayerConfiguration;
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
import org.eclipse.nebula.widgets.nattable.style.theme.DarkNatTableThemeConfiguration;
import org.eclipse.nebula.widgets.nattable.style.theme.DefaultNatTableThemeConfiguration;
import org.eclipse.nebula.widgets.nattable.style.theme.ModernNatTableThemeConfiguration;
import org.eclipse.nebula.widgets.nattable.ui.menu.HeaderMenuConfiguration;
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;

import com.vogella.tasks.model.Task;

import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.FilterList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.SortedList;

public class NattableExample {

    private static final Map<String, String> LABELS = Map.of("id", "ID", "summary", "Summary", "description",
            "Description", "done", "Done", "dueDate", "Due Date");

    @PostConstruct
    public void postConstruct(Composite parent) {
        parent.setLayout(new GridLayout(2, false));

        // 100,000 rows are no problem, NatTable only renders the visible cells
        EventList<Task> tasks = GlazedLists.threadSafeList(GlazedLists.eventList(createTasks(100_000)));
        SortedList<Task> sortedList = new SortedList<>(tasks, null);
        FilterList<Task> filterList = new FilterList<>(sortedList);

        ConfigRegistry configRegistry = new ConfigRegistry();
        IColumnPropertyAccessor<Task> accessor = new TaskColumnPropertyAccessor();
        ListDataProvider<Task> bodyDataProvider = new ListDataProvider<>(filterList, accessor);
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
        bodyDataLayer.setColumnWidthByPosition(0, 70);
        bodyDataLayer.setColumnWidthByPosition(1, 230);
        bodyDataLayer.setColumnWidthByPosition(2, 380);
        bodyDataLayer.setColumnWidthByPosition(3, 70);
        bodyDataLayer.setColumnWidthByPosition(4, 120);
        bodyDataLayer.setConfigLabelAccumulator(new ColumnLabelAccumulator());
        // refresh the table when the list changes, e.g., after a filter or an edit
        GlazedListsEventLayer<Task> eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, filterList);

        // body: column reorder, hide and show, group support, selection and viewport
        ColumnGroupModel columnGroupModel = new ColumnGroupModel();
        ColumnGroupBodyLayerStack bodyLayerStack = new ColumnGroupBodyLayerStack(eventLayer, columnGroupModel);
        bodyLayerStack.getSelectionLayer().addConfiguration(new DefaultRowSelectionLayerConfiguration());
        bodyLayerStack.getViewportLayer().setRegionName(GridRegion.BODY);

        // freeze: keeps the first columns visible while scrolling horizontally
        FreezeLayer freezeLayer = new FreezeLayer(bodyLayerStack.getSelectionLayer());
        CompositeFreezeLayer freezeComposite = new CompositeFreezeLayer(freezeLayer, bodyLayerStack.getViewportLayer(),
                bodyLayerStack.getSelectionLayer());

        // column header: labels, sorting, column groups and the filter row
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
                TaskColumnPropertyAccessor.propertyNames.toArray(new String[0]), LABELS);
        DataLayer columnHeaderDataLayer = new DefaultColumnHeaderDataLayer(columnHeaderDataProvider);
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, freezeComposite,
                bodyLayerStack.getSelectionLayer());
        SortHeaderLayer<Task> sortHeaderLayer = new SortHeaderLayer<>(columnHeaderLayer,
                new GlazedListsSortModel<>(sortedList, accessor, configRegistry, columnHeaderDataLayer));
        ColumnGroupHeaderLayer groupHeaderLayer = new ColumnGroupHeaderLayer(sortHeaderLayer,
                bodyLayerStack.getSelectionLayer(), columnGroupModel);
        groupHeaderLayer.addColumnsIndexesToGroup("Task", 0, 1, 2);
        groupHeaderLayer.addColumnsIndexesToGroup("Status", 3, 4);
        FilterRowHeaderComposite<Task> filterRowHeaderLayer = new FilterRowHeaderComposite<>(
                new DefaultGlazedListsFilterStrategy<>(filterList, accessor, configRegistry), groupHeaderLayer,
                columnHeaderDataProvider, configRegistry);

        // row header and corner
        DefaultRowHeaderDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
        DataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
        RowHeaderLayer rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, freezeComposite,
                bodyLayerStack.getSelectionLayer());
        CornerLayer cornerLayer = new CornerLayer(
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
                rowHeaderLayer, filterRowHeaderLayer);

        GridLayer gridLayer = new GridLayer(freezeComposite, filterRowHeaderLayer, rowHeaderLayer, cornerLayer);
        gridLayer.addConfiguration(new DefaultEditConfiguration());

        // theme chooser
        new Label(parent, SWT.NONE).setText("Theme");
        Combo themeCombo = new Combo(parent, SWT.READ_ONLY);
        themeCombo.setItems("Modern", "Dark", "Classic");
        themeCombo.select(0);

        NatTable natTable = new NatTable(parent, gridLayer, false);
        natTable.setConfigRegistry(configRegistry);
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
        natTable.addConfiguration(new SingleClickSortConfiguration());
        natTable.addConfiguration(new DefaultFreezeGridBindings());
        natTable.addConfiguration(new HeaderMenuConfiguration(natTable));
        natTable.addConfiguration(new TaskEditConfiguration());
        natTable.addConfiguration(new FilterRowConfiguration());
        natTable.configure();
        natTable.setTheme(new ModernTaskTheme());
GridDataFactory.fillDefaults().grab(true, true).span(2, 1).applyTo(natTable);

        // freeze the first two body columns, the ID and the Summary
        freezeComposite.doCommand(new FreezeColumnCommand(freezeComposite, 1, false, true));

        themeCombo.addListener(SWT.Selection, e -> natTable.setTheme(switch (themeCombo.getSelectionIndex()) {
        case 1 -> new DarkTaskTheme();
        case 2 -> new DefaultNatTableThemeConfiguration();
        default -> new ModernTaskTheme();
        }));
    }

    /** The modern theme with zebra rows and a light header. */
    static class ModernTaskTheme extends ModernNatTableThemeConfiguration {
        ModernTaskTheme() {
            Color header = GUIHelper.getColor(0xEE, 0xF1, 0xF6);
            this.oddRowBgColor = GUIHelper.getColor(0xF7, 0xF9, 0xFC);
            this.cHeaderBgColor = header;
            this.rHeaderBgColor = header;
            this.cornerBgColor = header;
            this.defaultSelectionBgColor = GUIHelper.getColor(0xD6, 0xE4, 0xFA);
            this.defaultSelectionFgColor = GUIHelper.COLOR_BLACK;
            this.cHeaderSelectionBgColor = header;
            this.cHeaderFullSelectionBgColor = header;
            this.rHeaderSelectionBgColor = this.defaultSelectionBgColor;
            this.rHeaderFullSelectionBgColor = this.defaultSelectionBgColor;
            this.cHeaderSelectionFgColor = GUIHelper.COLOR_BLACK;
            this.cHeaderFullSelectionFgColor = GUIHelper.COLOR_BLACK;
            this.rHeaderSelectionFgColor = GUIHelper.COLOR_BLACK;
            this.rHeaderFullSelectionFgColor = GUIHelper.COLOR_BLACK;
            this.selectionAnchorBgColor = this.defaultSelectionBgColor;
            this.selectionAnchorSelectionBgColor = this.defaultSelectionBgColor;
            this.selectionAnchorSelectionFgColor = GUIHelper.COLOR_BLACK;
            this.filterRowBgColor = GUIHelper.getColor(0xFB, 0xFC, 0xFE);
        }

        @Override
        protected Color getGridLineColor() {
            return GUIHelper.getColor(0xD9, 0xDE, 0xE6);
        }

        @Override
        protected Color getFreezeSeparatorColor() {
            return GUIHelper.getColor(0x7A, 0x8B, 0xA8);
        }
    }

    /** The dark theme with slate colors instead of the system colors. */
    static class DarkTaskTheme extends DarkNatTableThemeConfiguration {
        DarkTaskTheme() {
            Color background = GUIHelper.getColor(0x1E, 0x22, 0x2B);
            Color header = GUIHelper.getColor(0x2E, 0x34, 0x40);
            this.defaultBgColor = background;
            this.evenRowBgColor = background;
            this.oddRowBgColor = GUIHelper.getColor(0x25, 0x2A, 0x35);
            this.cHeaderGradientBgColor = header;
            this.cHeaderGradientFgColor = header;
            this.rHeaderGradientBgColor = header;
            this.rHeaderGradientFgColor = header;
            this.cornerGradientBgColor = header;
            this.cornerGradientFgColor = header;
            this.defaultSelectionBgColor = GUIHelper.getColor(0x35, 0x4A, 0x6E);
            this.selectionAnchorBgColor = this.defaultSelectionBgColor;
            this.selectionAnchorSelectionBgColor = this.defaultSelectionBgColor;
            this.filterRowBgColor = GUIHelper.getColor(0x28, 0x2E, 0x3A);
        }

        @Override
        protected Color getGridLineColor() {
            return GUIHelper.getColor(0x3B, 0x42, 0x52);
        }

        @Override
        protected Color getFreezeSeparatorColor() {
            return GUIHelper.getColor(0x7A, 0x8B, 0xA8);
        }
    }

    /** Makes all columns except the id editable and shows a checkbox for the done state. */
    static class TaskEditConfiguration extends AbstractRegistryConfiguration {
        @Override
        public void configureRegistry(IConfigRegistry configRegistry) {
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE,
                    IEditableRule.ALWAYS_EDITABLE);
            String idLabel = ColumnLabelAccumulator.COLUMN_LABEL_PREFIX + 0;
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE,
                    IEditableRule.NEVER_EDITABLE, DisplayMode.EDIT, idLabel);
            String doneLabel = ColumnLabelAccumulator.COLUMN_LABEL_PREFIX + 3;
            configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, new CheckBoxPainter(),
                    DisplayMode.NORMAL, doneLabel);
            configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER,
                    new DefaultBooleanDisplayConverter(), DisplayMode.NORMAL, doneLabel);
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new CheckBoxCellEditor(),
                    DisplayMode.EDIT, doneLabel);
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new TextCellEditor(),
                    DisplayMode.EDIT, ColumnLabelAccumulator.COLUMN_LABEL_PREFIX + 4);
        }
    }

    private static List<Task> createTasks(int count) {
        String[] verbs = { "Review", "Fix", "Update", "Document", "Refactor", "Test", "Deploy", "Plan" };
        String[] things = { "pull request", "login page", "build pipeline", "database schema", "API client",
                "release notes", "cache layer", "search index" };
        Random random = new Random(42);
        List<Task> tasks = new ArrayList<>(count);
        for (int i = 1; i <= count; i++) {
            String thing = things[random.nextInt(things.length)];
            tasks.add(new Task(i, verbs[random.nextInt(verbs.length)] + " " + thing,
                    "Follow-up for the " + thing + " of milestone " + (1 + i / 1000), random.nextInt(100) < 40,
                    LocalDate.now().plusDays(random.nextInt(365) - 90)));
        }
        return tasks;
    }
}

16.6. Validate

Start the application and open the part. The table starts with the modern theme. Try the following features.

  • Click twice on the ID header to sort the 100,000 rows in descending order.

  • Type (Fix|Test).* into the filter cell of the Summary column.

  • Scroll horizontally and see that the ID and Summary columns stay visible.

  • Drag a column header to another position or use the header menu to hide a column.

  • Double-click a cell to edit it, or click the checkbox in the Done column.

  • Select Dark in the theme chooser.

NatTable showing tasks with column groups, a filter row, a descending sorted ID column and a selected row in the modern theme
The same NatTable in the dark theme
Home Tutorials Training Consulting Books Company Contact us


Get more...