【发布时间】:2015-10-26 01:41:13
【问题描述】:
我有一个带有 AbstractTabelModel 的 JTable。我试图在我的项目中创建一个 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 添加到滚动窗格中。任何 cmets 或建议将不胜感激。
【问题讨论】:
-
您是否尝试过使用
setWidth?它的偏好和实际宽度之间存在差异 -
"如有任何 cmets 或建议,我们将不胜感激。" 如需更好的帮助,请尽快发帖 minimal reproducible example 或 Short, Self Contained, Correct Example。
-
@MadProgrammer 找到了答案。它基于此处所述使用的字体:stackoverflow.com/a/13234470/4012979
标签: java swing jtable preferredsize