How do I set the column width for selected columns in a JTable

For this line --->  table.getColumn(2).setPreferredWidth(10);
i am getting this ERROR --->>
Exception in thread "main" java.lang.IllegalArgumentException: Identifier not found
      at javax.swing.table.DefaultTableColumnModel.getColumnIndex(Unknown Source)
      at javax.swing.JTable.getColumn(Unknown Source)
      at browseSelect.main(browseSelect.java:113)

JTable table = new JTable(browseList, headersV);
               JScrollPane scrolls = new JScrollPane(table,
            		   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            		      JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
               table.getColumn(2).setPreferredWidth(10);

Open in new window

Vanavah EdwardsAsked:
Who is Participating?
 
for_yanConnect With a Mentor Commented:
you can look here:
http://stackoverflow.com/questions/953972/java-jtable-setting-column-width
but as you see it is rather painful
0
 
for_yanCommented:

look here:
http://www.exampledepot.com/egs/javax.swing.table/ColSize.html

int rows = 3;
int cols = 3;
JTable table = new JTable(rows, cols);

// Disable auto resizing
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

// Set the first visible column to 100 pixels wide
int vColIndex = 0;
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int width = 100;
col.setPreferredWidth(width);

Open in new window

0
 
for_yanCommented:
But befire you do anything - popuate your table and look at it.
Why do you want to chaneg column size?
In majority of tables you dont need to do it
0
 
for_yanCommented:
As you see to do it - you need to disable autoaddjustment - so you'll take a lot of unneccassry responsibilities upon yourself - let
swing do its job - it ill in most case do a better job
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.