Auto resize the widths of JTable's columns dynamically

Viewed 28080

I have a JTable with 3 columns:

- No. #
- Name
- PhoneNumber

I want to make specific width for each column as follows:

enter image description here

and I want the JTable able to update the widths of its columns dynamically if needed (for example, inserting large number in the column #) and keeping same style of the JTable

I solved the first issue, using this code:

myTable.getColumnModel().getColumn(columnNumber).setPreferredWidth(columnWidth);

but I didn't success to make myTable to update the widths dynamically ONLY if the current width of the column doesn't fit its contents. Can you help me solving this issue?

3 Answers

I actually run into this problem too. I've found one useful link that solved my issue. Pretty much get the specific column and set its setMinWidth and setMaxWidth to be the same(as fixed.)

private void fixWidth(final JTable table, final int columnIndex, final int width) {
    TableColumn column = table.getColumnModel().getColumn(columnIndex);
    column.setMinWidth(width);
    column.setMaxWidth(width);
    column.setPreferredWidth(width);
}

Ref: https://forums.oracle.com/thread/1353172

Related