How can you set fixed column width in a JTable in Java?

In Java, you can set fixed column widths by setting the column model of a JTable. You can use the setPreferredWidth method of the TableColumn class to set the width of a column, for example:

TableColumn column = table.getColumnModel().getColumn(columnIndex);

column.setPreferredWidth(width);

In the given code, ‘table’ is a JTable object, ‘columnIndex’ is the index of the column whose width needs to be set (starting from 0), and ‘width’ is the desired width value to be set. If you want to set the width of multiple columns, you can call the setPreferredWidth method multiple times in the code above. Additionally, if you want the column width to automatically adjust to fit the width of the cell content, you can use the setAutoResizeMode method to set the mode for automatically adjusting column width.

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

As a result, a horizontal scroll bar will automatically appear when the content in the table exceeds the width of the columns.

bannerAds