I have a JTable in which I set the column size as follows:
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(400);
This works fine, but when the table is maximized, I get empty space to the right of the last column. Is it possible to make the last column resize to the end of the window when resized?
I found AUTO_RESIZE_LAST_COLUMN
property in docs but it does not work.
Edit: JTable
is in a JScrollPane
its prefered size is set.
will default the resize behavior ! If this method is called somewhere in your code AFTER you did set the column resize properties all your settings will be reset. This side effect can happen indirectly. F.e. as a consequence of the linked data model being changed in a way this method is called, after properties are set.
What happens if you call
setMinWidth(400)
on the last column instead ofsetPreferredWidth(400)
?In the JavaDoc for
JTable
, read the docs fordoLayout()
very carefully. Here are some choice bits:This might be why
AUTO_RESIZE_LAST_COLUMN
didn't help you.This says that you might want to set Min == Max for all but the last columns, then set Min = Preferred on the last column and either not set Max or set a very large value for Max.
Use this method
Or extend the
JTable
class:And then
Use this code. It worked for me. I considered for 3 columns. Change the loop value for your code.
With
JTable.AUTO_RESIZE_OFF
, the table will not change the size of any of the columns for you, so it will take your preferred setting. If it is your goal to have the columns default to your preferred size, except to have the last column fill the rest of the pane, You have the option of using theJTable.AUTO_RESIZE_LAST_COLUMN
autoResizeMode, but it might be most effective when used withTableColumn.setMaxWidth()
instead of TableColumn.setPreferredWidth() for all but the last column.Once you are satisfied that
AUTO_RESIZE_LAST_COLUMN
does in fact work, you can experiment with a combination ofTableColumn.setMaxWidth()
andTableColumn.setMinWidth()
JTable.AUTO_RESIZE_LAST_COLUMN
is defined as "During all resize operations, apply adjustments to the last column only" which means you have to set the autoresizemode at the end of your code, otherwise setPreferredWidth() won't affect anything!So in your case this would be the correct way: