Re: How can I resize a JTable's column width?

From: Pacific Guy (
Date: 06/25/04

Date: 25 Jun 2004 13:49:31 -0700 (gajo) wrote in message news:<>...
> Hi,
> I've created a JTable and filled it out with some data, but by default the
> table's header is filled out by values like A,B,C,... So I've created a new
> JTableHeader which is wrapped around a DefaultTableColumnModel object that
> I've created and to which I have added the neccessary columns and set their
> size and text.
> After I start the application, the header of the table looks good, but the
> table columns do not follow the header's column's width. That is, the width
> of the header's columns are not equals to the table's.
> I tried to make the table's column model the same as the header's, by doing
> table.setColumnModel(myColumns); but instead of getting what I wanted I've
> got an empty table (the values I entered did not show up), and all the
> column widths were equal and set to some default value. I could tollerate
> even that, but why don't the cell values show up? I tried revalidating,
> repainting and doLayout(), but nothing works.
> So what should I do to customize the table's column width to be equal to
> that of the headers?
> And btw. how can I add a scrollbar to the table? Wrapping a ScrollPane
> around it doesn't seem to work!

I'm not sure what you're using as the datamodel for your table, but if
you're using a custom object as opposed to a simple array, implement
it's public String getColumnName(int idx){} method to return the
correct column name. If you do that the JTable will output the correct
column header names and your column header widths will stay synched up
with the widths of the table columns.

If you are using simple arrays, follow the constructor example at the
top of this tutorial to display column headers with simple data from

> Here's some code for further explanation, just in case:
> // I create the table
> myTable = new JTable(numRows, 3);
> // I create the column model
> TableColumn firstCol = new TableColumn();
> firstCol.setHeaderValue("Red");
> firstCol.setWidth(50);
> TableColumn secondCol = new TableColumn();
> secondCol.setHeaderValue("Blue");
> secondCol.setWidth(80);
> TableColumn thirdCol = new TableColumn();
> thirdCol.setHeaderValue("Brown");
> thirdCol.setWidth(40);
> DefaultTableColumnModel myCols= new DefaultTableColumnModel();
> myCols.addColumn(firstCol);
> myCols.addColumn(secondCol);
> myCols.addColumn(thirdCol);
> // I set the table's header
> myTable.setTableHeader(new JTableHeader(myCols));
> // if I do this the cell values won't show
> // myTable.setColumnModel(myCols);
> // I add the data to the cells
> for (int i = 0; i<numRows; i++) {
> myTable.setValueAt("bear", i, 0);
> myTable.setValueAt("fox", i, 0);
> myTable.setValueAt("pheasant", i, 0);
> }