简体   繁体   English

JTable设置列宽不起作用

[英]JTable set column width not working

I am trying to set column width to the length of the column name. 我正在尝试将列宽设置为列名的长度。 My problem is, I am not able to set it. 我的问题是,我无法设置它。 When I use the following code the table is becoming like this, 当我使用以下代码时,表格变得像这样,

tableA.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
  for(int i = 0; i < tableA.getColumnCount(); i++) {
int columnLength = (modelA.getColumnName(i)).length();
tableA.getColumnModel().getColumn(i).setPreferredWidth(columnLength);
//  tableA.getColumnModel().getColumn(i).setMinWidth(columnLength);
//  tableA.getColumnModel().getColumn(i).setMaxWidth(columnLength);
  }

I am getting the column length correctly from my table model. 我从我的表模型中正确获取列长度。

When I use the above code the table is getting packed like this, 当我使用上面的代码时,表会像这样被打包,

设置列宽

I am not able to understand where I am doing wrong. 我无法理解我在哪里做错了。

As Dan has pointed out, you need to calculate the actual width of the column name based on the Font that is being used. 正如Dan所指出的,您需要根据所使用的Font计算列名的实际宽度。

Something like: 就像是:

String name = modelA.getColumnName(i);
Font f = tableA.getFont();
FontMetrics fm = tableA.getFontMetrics(f);
int width = fm.stringWidth(name);
tableA.getColumnModel().getColumn(i).setPreferredWidth(width);

Note that this is an extremely abbreviated example. 请注意,这是一个极其简短的示例。

If you want to get it completely correct, you will need to query each column's renderer for the Font and the FontMetrics in order to get the correct values. 如果要使其完全正确,则需要在每列的渲染器中查询Font和FontMetrics,以获取正确的值。

If all your renderers use the same font as the JTable, then this should be OK. 如果所有渲染器都使用与JTable相同的字体,则应该可以。

所述setPreferredWidth预计像素的值,而该列名的长度为a的长度String (字符在多个String )。

如果您不介意使用SwingX,则可以使用TableColumnExt#setPrototypeValue方法,该方法允许您设置“原型”值,该值将用于确定列宽。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM