0

I have created a jTable with 0 rows and 0 columns since the contents,including header names, are going to be added dynamically based on buttons. I'm using a TableCellrenderer to resize the columns. In my code all the columns are arranging only based on header values and moreover if the sum of all the column widths is less than that of the jTable width, it should cover the entire table. I don't know how to do that and whats the problem in my code. Thanks in advance

public void tableresize(JTable table)
{
  for(int i=0;i<table.getColumnCount();i++)
  { 
    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
    TableColumn col = colModel.getColumn(i);
    int width = 0;
    TableCellRenderer renderer = col.getHeaderRenderer();
    if (renderer == null)
    {
      renderer = table.getTableHeader().getDefaultRenderer();
    }
    Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, i);  
    if(table.getRowCount()>0)
    {
      for(int r=0;r<table.getRowCount();r++)
      {
        renderer=table.getCellRenderer(r,i);
        Component comp1=renderer.getTableCellRendererComponent(table,table.getValueAt(r, i),false,false, r, i);     
        if(comp.getPreferredSize().width<comp1.getPreferredSize().width)
        {
          width=comp1.getPreferredSize().width;
        }
        else
        {
          width=comp.getPreferredSize().width;
        }
      }
    }
    else
    {
      width=comp.getPreferredSize().width;
    }  
    col.setPreferredWidth(width+4);      
  }    
}
Previnkumar
  • 107
  • 3
  • 13

1 Answers1

0

In my code all the columns are arranging only based on header values

Well, I would guess you only invoke your code when the row count is 0.

Check out the Table Column Adjuster for a class to calculate column widths. The code can be invoked dynamically as you add/remove rows of data or change the data in a cell.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Thanks for help. It works. But if sum of width of all my columns is less than the total width, all the columns are arranged on one side(columns donot fully cover the table) – Previnkumar Jun 30 '17 at 16:35
  • @previn, I have never tried it, but you might be able to combine the above class with the suggestion in this posting: https://stackoverflow.com/questions/15234691/enabling-auto-resize-of-jtable-only-if-it-fit-viewport/15240806#15240806 – camickr Jun 30 '17 at 20:46
  • I got the solution with above class by using some extra conditions . If the total width is too low i enable AUTO_RESIZE_ALL_COLUMNS.. Working pretty good. Thanks – Previnkumar Jul 01 '17 at 13:50