table 列的 setPreferredWidth() 显示不正确

setPreferredWidth() for table column display incorrectly

我有一张 table 像这张图片,它不包含任何数据

所以我想删除发送列后的空格,我正在使用

table.getColumnModel().getColumn(0).setPreferredWidth(5);   //first column size
System.out.println(table.getColumnModel().getColumn(0).getPreferredWidth());

但它打印 15 !!
如果我将 setPreferredWidth 设置为大于 15 的数字,它会影响列
但是如果我将 setPreferredWidth 设置为小于 15 的数字,它不会影响该列,默认情况下它需要 15

我该如何解决?

在您的情况下,使用 setMaxWidth(int) 不仅可以定义首选尺寸,还可以定义最大尺寸

table.getColumnModel().getColumn(0).setPreferredWidth(5);
table.getColumnModel().getColumn(0).setMaxWidth(5);
System.out.println(table.getColumnModel().getColumn(0).getPreferredWidth());

输出:

5