我有一个 JTable,其中显示了 AbstractTabelModel。我尝试在项目中创建一个 void 方法,将每列的宽度设置为列中最长值的长度。这是我现在使用的方法,其中“accountWindow”是 JTable:
public void setColumnWidths(){
accountWindow.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int i = 0; i < accountWindow.getColumnCount(); i++){
int greatestStringLength = 2;
for (int z = 0; z < accountWindow.getRowCount(); z++){
if (accountWindow.getValueAt(z, i).toString().length() > greatestStringLength){
System.out.println("Width SET");
greatestStringLength = accountWindow.getValueAt(z, i).toString().length();
accountWindow.getColumnModel().getColumn(i).setPreferredWidth(greatestStringLength);
}
//System.out.println(accountWindow.getValueAt(z, i).toString());
//System.out.println("Greatest Value: " + greatestValueWidth);
}
}
}
该方法在我的 Controller 类 (MVC) 中被正确调用,但它将每列的宽度基本上设置为 0。更新表和 fireTableData() 方法之后调用该方法被调用并显示帐户信息。我已将 JTable 添加到滚动 Pane 。如有任何意见或建议,我们将不胜感激。
最佳答案
宽度需要以像素为单位指定,而不是字符串中的字符。
if (accountWindow.getValueAt(z, i).toString().length() > greatestStringLength){
在我看来,您只是获取字符串中的字符数,而不是渲染字符串所需的宽度。也就是说 20 个字符不会在 20 个像素中呈现。不同字体的字符串宽度会有所不同。
查看Table Column Adjuster有关如何确定渲染宽度的解决方案。它提供了一个简单的用法和一个您可以使用的具有更多功能的自定义类。
两种解决方案实际上都会调用表格使用的渲染器来确定最大宽度。
关于java - JTable setPreferredWidth() 用于显示不正确的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33337231/