wiki:EclipseTutorial_ControllingColumnRelativeWidth

Controlling Columns Relative Width for Expanding Trees and Columns

While expanding or contracting Tables and Trees, it is sometimes desirable to expand all the columns of the control relatively. Say for example, while expanding a Table with columns for name and id where the column for name is twice as wider as the column for id, and one would like to expand the columns in the same ratio. To achieve this one needs to add a ControlListener to the Table. Inside the ControlListener class one recalculates the width and re-assigns them to the appropriate columns.

      // code to add the control listener

      MaintainTableColumnRatioListener ratioController = new MaintainTableColumnRatioListener(1000, 1, 3);
      tableViewer.getTable().addControlListener(ratioController);

One needs to implament this inside the void:controlResized(ControlEvent)

   public class SomeListener implements ControlListener
   {
      @Override
      public void controlResized(ControlEvent e)
      {
         Table table = (Table) e.getSource();
         tablesTotalWidth = table.getSize().x;
         
         int currentWidth = 0;

         newWidthForColumn0 = getNewWidthFromSomeFormula(tablesTotalWidth, 0);
         (table.getColumns()[0]).setWidth(newWidthForColumn0);
         currentWidth += newWidthForColumn0 ;

         newWidthForColumn1 = getNewWidthFromSomeFormula(tablesTotalWidth, 1);
         (table.getColumns()[1]).setWidth(newWidthForColumn1);
         currentWidth += newWidthForColumn0 ;

         // add other columnWidths till second last column


         // for last column add the remaining width as it would help eliminate 
         // extra/uncounted width for widths formula might not divide among integer values

         newWidthForlastColumn = tablesTotalWidth  - currentWidth;
         (table.getColumns()[lastColumn]).setWidth(newWidthForlastColumn);

      }

      private void getNewWidthFromSomeFormula(int tablesTotalWidth, int columnNo)
      {
         // implement the formula
      }
 
      @Override
      public void controlMoved(ControlEvent e)
      {
        
      }
   }

The Sample Plugin also contains a generic control listener for Tree and another for Table.

One can use this listener by giving the minimum width and the desired relative widths of the columns in the constructor (as many columns are there). The relative widths should atleast be 1 for each column.

Last modified 8 years ago Last modified on 10/28/2014 11:01:49 PM