3
votes

Is it possible to load data lazily into a GWT DataGrid, similarly to how the GWT CellList lazily loads data?

I have a GWT DataGrid that can potentially bring back hundreds of rows, but only about 20 rows are displayed at a time. When this occurs, the loading of the grid is quite slow.

I want to use a DataGrid instead of a CellTList because I have multiple columns of data that need to be displayed. And I've opted for a DataGrid instead of a CellTable because I want the header columns to be fixed.

1
CellList and DataGrid are both cellview widgets, so the same technique you apply to "lazy loading" a CellList will work for DataGrid. Have you tried? - Strelok
I have implemented this as a CellTable, and this works. When I do it with a DataGrid, however, I believe the scrollbar being shown is the one generated by the DataGrid, not the one generated by the ScrollPanel. I wanted to use a DataGrid because I want the headers to remain visible as scrolling occurs. - vincentvanjoe

1 Answers

8
votes

Since DataGrid doesn't expose it's ScrollPanel, create an inner class that extends DataGrid and provides a reference to the ScrollPanel:

private static class MyDataGrid<T> extends DataGrid {
    public ScrollPanel getScrollPanel() {
        HeaderPanel header = (HeaderPanel) getWidget();
        return (ScrollPanel) header.getContentWidget();
    }
}

Initialize the variables needed for this to work:

private MyDataGrid<MyDataType> myDataGrid;
private int incrementSize = 20;
private int lastScrollPos = 0;

In the constructor, create the grid:

myDataGrid = new MyDataGrid<MyDataType>();

Then add a ScrollHandler, using the getScrollPanel() reference that was just created:

myDataGrid.getScrollPanel().addScrollHandler(new ScrollHandler(){

    @Override
    public void onScroll(ScrollEvent event) {

        int oldScrollPos = lastScrollPos;
        lastScrollPos = myDataGrid.getScrollPanel().getVerticalScrollPosition();

        // If scrolling up, ignore the event.
        if (oldScrollPos >= lastScrollPos) {
            return;
        }

        //Height of grid contents (including outside the viewable area) - height of the scroll panel
        int maxScrollTop = myDataGrid.getScrollPanel().getWidget().getOffsetHeight() - 
                           myDataGrid.getScrollPanel().getOffsetHeight();

        if(lastScrollPos >= maxScrollTop) {
            myDataGrid.setVisibleRange(0,myDataGrid.getVisibleRange().getLength()+incrementSize);
        }
    }
});