javaswtscrollbarjfacetableviewer

JFace TableViewer get visible column width


I have a TableViewer with horizontal scrollbar. Moving the scrollbar or re-sizing window can hide or show certain columns.

I want to know if a certain column is visible after scrolling and if so, its exact width that is visible.

Any way to do it?


Solution

  • You need to query the underlying Table (viewer.getTable()) and its TableColumns (table.getColumns()) to solve this.

    If you defined the viewers columns using TableViewerColumns the columns are also accessible through viewerColumn.getColumn().

    To determine the rightmost visible column, you can use the width of the table's clientArea (Table#getClientArea().width) that gives you the total available space to show columns.

    Each column has a width TableColumn.getWidth(). Adding all the widths of the columns that are left of the desired one, will enable you to dermine if it is visible.

    table.getHorizontalBar().getSelection() gives you the horizontal offset of the rows. When substracting this offset you should be able to dermine if a given column is visible.

    The resulting code would look like this:

    boolean isColumnVisible(Table table, int columnIndex) {
      int columnRight = 0;
      for( int i = 0; i <= columnIndex; i++ ) {
        columnRight += table.getColumn(i).getWidth();
      }
      int clientAreaWidth = table.getClientArea().width;
      int horizontalOffset = table.getHorizontalBar().getSelection();
      return columnRight - horizontalOffset <= clientAreaWidth;
    }
    

    Note that if the columns can be re-ordered you need to determine the actual columnIndex through table.getColumnOrder()