JTable设置列宽不起作用 [英] JTable set column width not working

查看:299
本文介绍了JTable设置列宽不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将列宽设置为列名的长度.我的问题是,我无法设置它.当我使用以下代码时,表格将变成这样,

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.

推荐答案

正如Dan所指出的,您需要根据所使用的Font计算列名的实际宽度.

As Dan has pointed out, you need to calculate the actual width of the column name based on the Font that is being used.

类似的东西:

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.

如果要使其完全正确,则需要查询每列的 renderer 中的Font和FontMetrics,以获取正确的值.

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.

如果所有渲染器都使用与JTable相同的字体,则应该可以.

If all your renderers use the same font as the JTable, then this should be OK.

这篇关于JTable设置列宽不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆