Search code examples
javapaginationswttableviewer

how to do paging for TableViewer jface?


I created application with TableViewer in eclipse. The TableViewer is import from org.eclipse.jface.viewers.TableViewer

The table has a lot of data.

When I scroll on the table I want to see the next result of the table (Paging)

Do you know if there is something generic for this ?


Solution

  • Here is some code that will do what (I think) you want:

    private static int page = 0;
    private static int pageSize = 10;
    
    public static void main(String[] args)
    {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setLayout(new FillLayout());
    
        final Table table = new Table(shell, SWT.NONE);
        table.addListener(SWT.MouseWheel, new Listener()
        {
            @Override
            public void handleEvent(Event e)
            {
                if(e.count < 0)
                    addItems(table, page++);
                else if(e.count > 0)
                    addItems(table, page--);
            }
        });
    
        addItems(table, page);
    
        shell.pack();
        shell.open();
        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
                display.sleep();
        }
        display.dispose();
    }
    
    private static void addItems(Table table, int topIndex)
    {
        table.removeAll();
        for(int i = 0; i < pageSize; i++)
        {
            TableItem item = new TableItem(table, SWT.NONE);
            item.setText("Item: " + (i + (topIndex * pageSize)));
        }
    }
    

    It will listen for MouseWheel events on the Table and update the content accordingly.


    Same holds for TableViewers instead of Tables, just replace the Listener with this:

    table.addListener(SWT.MouseWheel, new Listener()
    {
        @Override
        public void handleEvent(Event e)
        {
            if(e.count < 0)
                viewer.setInput(ModelProvider.INSTANCE.getItems(page++));
            else if(e.count > 0)
                viewer.setInput(ModelProvider.INSTANCE.getItems(page--));
        }
    });