tags:

views:

267

answers:

2

I am creating a GUI program and I need a table with different sized columns. How do I change it so that the 1st column is smaller than the 2nd and 3rd column?

+3  A: 

You need to get a handle to the TableColumnModel, and from there you are able to set the individual column widths. For example:

JTable tbl = new JTable();
TableColumnModel colMdl = tbl.getColumnModel();
colMdl.getColumn(0).setPreferredWidth(100);
colMdl.getColumn(1).setPreferredWidth(150);
colMdl.getColumn(2).setPreferredWidth(150);

Also, here's some useful example code showing how to "pack" a given column to be wide enough to show all values in the JTable. I typically use a modified version of this in my GUIs and will "pack" the table when the first row is added to it - After this I allow the user to control the widths.

Adamski
when I try and compile, it says cannot find symbol - class TableColumnModel
Karen
You'll need to import it at the top of your .java file: import javax.swing.table.TableColumnModel.
Adamski
I've got import javax.swing.*;It worked when I did DefaultTableColumnModel colModel = (DefaultTableColumnModel)table.getColumnModel();Is that right? When I try to set it to a really small width like 5, the columns become the same width again. Is that too small?
Karen
You shouldn't need to cast the column model to a DefaultTableColumnModel; all the methods you need are on the TableColumnModel interface. You can either explicitly import this (as I mentioned above or import javax.swing.table.* as well as javax.swing.*). Regarding the sizing issues you may need to set the minimum width to 0 (setMinWidth method) as well as the preferred width.
Adamski
I tried importing all the files you mentioned above, but I still got the error..
Karen
Please post your code.
Adamski
Try setting the autoresize of the columns off:JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
Telcontar
A: 

Have you read the Swing tutorial yet? All you questions are basic and are covered in the tutorial.

You will find the tutorial has a working example that does exactly this. We should not have to spend time reminding you to read the tutorial FIRST before posting a question.

"Teach somebody to fish and they eat for life. Give somebody a fish and they eat for a day."

(and then they come back and ask another question, which is why spoonfeeding answers is not a good idea.)

camickr