2

I have a JTable built using DefaultModel which is displayed in JPane but I would like to re-size the table to make it bigger. Could any one please explain how I could do that? I have tried the following code:

TableColumnModel colsize = t1.getColumnModel();

for(int i=0; i<cols; i++){

    colsize.getColumn(i).setPreferredWidth(200);
}

but it did not work.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sarah
  • 133
  • 1
  • 9
  • Do you want to make JTable bigger or change width of Column? – Smit Apr 09 '13 at 22:48
  • @smit the column mainly but I believe the column are not re-sizing due to the table size since in the view i can re-size the cloumn but making one column bigger result with the next column to be small to fit within the same table boundary. So I need to make the JTable bigger – Sarah Apr 09 '13 at 22:59

2 Answers2

4

To size up the table#setPreferredSize().

table.setPreferredSize(new Dimension(500, 500));

To size up the columns table#getColumn().

table.getColumn(columnNames[0]).setPreferredWidth(100);
table.getColumn(columnNames[1]).setPreferredWidth(400);

I hope this will help to resolve your issue. If you got any issue while implementing this then just ask.

Smit
  • 4,685
  • 1
  • 24
  • 28
  • thanks this help. Is there a way to setPerferredWidth() based on the lenght of the value at that column – Sarah Apr 09 '13 at 23:32
  • You have to put int value to specify width. So you can calculate that width part and you can set that calculated value. – Smit Apr 09 '13 at 23:39
3

Using setPreferredSize() is problematic. Because JTable implements Scrollable, overriding getPreferredScrollableViewportSize() to return a multiple of getRowHeight() may be a better approach.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045