【问题标题】:Auto resize the widths of JTable's columns dynamically动态自动调整 JTable 列的宽度
【发布时间】:2011-06-23 00:06:15
【问题描述】:

我有一个包含 3 列的 JTable:

- No. #
- Name
- PhoneNumber

我想为每一列设置特定的宽度,如下所示:

并且我希望 JTable 能够在需要时动态更新其列的宽度(例如,在 # 列中插入大量数字)并保持 JTable 的相同样式

我用这段代码解决了第一个问题:

myTable.getColumnModel().getColumn(columnNumber).setPreferredWidth(columnWidth);

但我没有成功让 my​​Table 仅当列的当前宽度不适合其内容时才动态更新宽度。你能帮我解决这个问题吗?

【问题讨论】:

    标签: java jtable


    【解决方案1】:

    在这里我找到了答案:http://tips4java.wordpress.com/2008/11/10/table-column-adjuster/
    这个想法是检查某些行的​​内容长度以调整列宽。
    在文章中,作者在可下载的 java 文件中提供了完整的代码。

    JTable table = new JTable( ... );
    table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
    
    for (int column = 0; column < table.getColumnCount(); column++)
    {
        TableColumn tableColumn = table.getColumnModel().getColumn(column);
        int preferredWidth = tableColumn.getMinWidth();
        int maxWidth = tableColumn.getMaxWidth();
    
        for (int row = 0; row < table.getRowCount(); row++)
        {
            TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
            Component c = table.prepareRenderer(cellRenderer, row, column);
            int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
            preferredWidth = Math.max(preferredWidth, width);
    
            //  We've exceeded the maximum width, no need to check other rows
    
            if (preferredWidth >= maxWidth)
            {
                preferredWidth = maxWidth;
                break;
            }
        }
    
        tableColumn.setPreferredWidth( preferredWidth );
    }
    

    【讨论】:

      【解决方案2】:

      使用 DefaultTableModel 的 addRow(...) 方法将数据动态添加到表中。

      更新:

      要调整可见列的宽度,我认为您需要使用:

      tableColumn.setWidth(...);
      

      【讨论】:

      • 哎呀,我想让JTable动态更新宽度,但是我写的是让JTable动态更新,对不起
      • 顺便说一句,接受的答案实际上是你的;)
      【解决方案3】:

      其实我也遇到过这个问题。我找到了一个有用的链接来解决我的问题。 几乎获取特定列并将其 setMinWidth 和 setMaxWidth 设置为相同(固定)。

      private void fixWidth(final JTable table, final int columnIndex, final int width) {
          TableColumn column = table.getColumnModel().getColumn(columnIndex);
          column.setMinWidth(width);
          column.setMaxWidth(width);
          column.setPreferredWidth(width);
      }
      

      参考:https://forums.oracle.com/thread/1353172

      【讨论】:

        猜你喜欢
        • 2023-03-29
        • 2015-03-27
        • 2014-01-14
        • 1970-01-01
        • 2015-01-27
        • 1970-01-01
        • 2016-08-01
        • 1970-01-01
        相关资源
        最近更新 更多