Tuesday, March 31, 2015

Lazy Load Data in a GWT DataGrid


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

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

myDataGrid = new MyDataGrid<MyDataType>();

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);
        }
    }
});

No comments: