gpt4 book ai didi

java - 调整 JTable 列的宽度

转载 作者:行者123 更新时间:2023-12-01 09:47:50 25 4
gpt4 key购买 nike

我指的是这个页面。 https://tips4java.wordpress.com/2008/11/10/table-column-adjuster/在 Jtable 中调整我的列宽度,它工作得很好。

但是有些列不是首选宽度,有人可以帮助我找出代码中的问题出在哪里吗?

我已在我的项目中附加了 Jtable 镜像。

学生详细信息的 Jtable 图像:

/image/owhW6.png

 public void resizeColumnWidth() {
for (int column = 0; column < student_table.getColumnCount(); column++)
{
TableColumn tableColumn = student_table.getColumnModel().getColumn(column);
int preferredWidth = tableColumn.getMinWidth();
int maxWidth = student_table.getColumnModel().getColumn(column).getMaxWidth();

for (int row = 0; row < student_table.getRowCount(); row++)
{
TableCellRenderer cellRenderer = student_table.getCellRenderer(row, column);
Component c = student_table.prepareRenderer(cellRenderer, row, column);
int width = c.getPreferredSize().width + student_table.getIntercellSpacing().width;
preferredWidth = Math.max(preferredWidth, width);

if (preferredWidth >= maxWidth)
{
preferredWidth = maxWidth;
break;
}
}

tableColumn.setPreferredWidth( preferredWidth );
}
}

最佳答案

But some columns are not in preferred width

如果您指的是 header 中的名称被截断,则问题在于您使用的代码仅考虑数据。如果您希望考虑标题宽度,则需要使用实际的 TableColumnAdjuster 类来实现完整功能。

如果您只是担心每个单元格中的数据,那么您仍然存在潜在问题:

int maxWidth = student_table.getColumnModel().getColumn(column).getMaxWidth();  

你设置了每列的最大宽度吗?

我认为默认值为 75 像素。

请注意,如果您不想限制列级别的宽度,则可以使用如下值:Integer.MAX_VALUE

另外,为什么要更改链接中示例代码的代码?您已经拥有对 TableColumn 的引用,那么为什么还要再次获取该引用呢?除非有特定原因,否则请勿更改代码示例。

关于java - 调整 JTable 列的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37841562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com