如何确定JTable中的哪些列可见

arc*_*rcy 3 java swing jtable

我正在根据他们的数据调整我的列的大小如下:

  /**
   * Set the widths of the columns in the table according to the data in the table.
   * @param table
   */
  private static void setColumnWidths(JTable table)
  {
    int columnCount = table.getModel().getColumnCount();
    int rowCount = table.getModel().getRowCount();

    TableColumnModel columnModel = table.getColumnModel();

    for (int col=0; col<columnCount; col++)
    {
      TableColumn column = columnModel.getColumn(col);
      TableCellRenderer renderer = column.getCellRenderer();
      if (renderer == null)
      {
        renderer = new DefaultTableCellRenderer();
      }
      int overallColumnWidth = 0;
      for (int row = 0; row < rowCount; row++)
      {
        Object value = table.getValueAt(row, col);
        Component component = renderer.getTableCellRendererComponent(table, value, false, false, row, col);
        int componentWidth = (int) component.getPreferredSize().getWidth();
        overallColumnWidth = Math.max(componentWidth, overallColumnWidth);
      }
      column.setPreferredWidth(overallColumnWidth);
    }
  }
Run Code Online (Sandbox Code Playgroud)

当所有列都可见时,这可以工作,但我有代码隐藏了其中的一些(JTable.removeColumn(TableColumn column)).看起来JTable实例和TableColumnModel实例都有数据列列表,即所有列都与可见性无关.如何获取仅显示可见列的列表,或者测试给定列是否可见?

(我已经搜索了这个,但是获得了关于如何隐藏列的文章列表,并没有解释保存可见/不可见信息的位置.我想,因为我要求JTable隐藏列,在某处它会知道隐藏了哪些列,我可以获得该信息.)

Man*_*anu 6

检查是否table.convertColumnIndexToView(col)返回-1.

从文档:

public int convertColumnIndexToView(int modelColumnIndex)

将modelColumnIndex中表模型中列的索引映射到视图中列的索引.返回视图中相应列的索引; 如果未显示此列,则返回-1.如果modelColumnIndex小于零,则返回modelColumnIndex.

资源