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