JTable column widths

Hi,

I would like to make a table such that, when the table gets populated with data from the TableModel, the columns that appear in the table are the width of the heading. So that the whole column heading is visible and the user doesn't have to manually expand the colum width.

Here are some code snippets...

privatevoid createTableModel(String query)throws SQLException{

System.out.println(query);

rs = stmt.executeQuery(query);

if (scrolling){

if (transType.equals("Parcel Lookup")){

tableModel =new ParcelLookUpHISTableModel(rs, tableName);

}else{

tableModel =new ScrollingHISTableModel(rs, tableName);

}

}else{

tableModel =new CachingHISTableModel(rs);

}

}

private JTable setUpTable(){

JTable table =new JTable(tableModel);

table.setSelectionForeground(Color.white);

table.setSelectionBackground(Color.red);

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

return table;

}

now when i get the table in the JScrollPane and show it, the table is fine but the column widths are all one equal size.

JScrollPane scrollPane =new JScrollPane(table);

informationPanel.setLayout(new GridBagLayout());

GridBagConstraints gbc =new GridBagConstraints();

gbc.gridx = 0;

gbc.gridy = 0;

gbc.gridwidth = 6;

gbc.gridheight = 6;

gbc.fill = GridBagConstraints.HORIZONTAL;

informationPanel.add(scrollPane, gbc);

Is there a logical way around this?

Thank You,

-Uday

[2519 byte] By [uday_prakasha] at [2007-11-27 2:21:07]
# 1

Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#width]How to Use Tables[/url] for an example of manually setting the column widths.

You need to calculate the width yourself. Generally you would use the FontMetrics class to determine the width of the text. Search the forum and you should find example solutions.

camickra at 2007-7-12 2:23:19 > top of Java-index,Desktop,Core GUI APIs...
# 2
camickr, many thanks...I did look at the Sun tutorial for the width setting. I didnt know about the font width, but the tutorial did help a lot. -Uday
uday_prakasha at 2007-7-12 2:23:19 > top of Java-index,Desktop,Core GUI APIs...