• category: swing folder: TableFileList title: JTableで文字列をクリックした場合だけセルを選択状態にする tags: [JTable, TableCellRenderer] author: aterai pubdate: 2006-12-25T16:51:36+09:00 description: JTableの文字列以外の場所がクリックされた場合、そのセルが選択されないようにします。 image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTUdT6R-SI/AAAAAAAAAmE/AYebcaiE77Y/s800/TableFileList.png hreflang:
       href: https://java-swing-tips.blogspot.com/2010/01/make-explorer-like-jtable-file-list.html
       lang: en

概要

JTableの文字列以外の場所がクリックされた場合、そのセルが選択されないようにします。

サンプルコード

// @see SwingUtilities2.pointOutsidePrefSize(...)
private static Rectangle getCellRect2(JTable table, int row, int col) {
  TableCellRenderer tcr = table.getCellRenderer(row, col);
  Object value = table.getValueAt(row, col);
  Component cell = tcr.getTableCellRendererComponent(table, value, false, false, row, col);
  Dimension itemSize = cell.getPreferredSize();
  Rectangle cellBounds = table.getCellRect(row, col, false);
  cellBounds.width = itemSize.width;
  return cellBounds;
  // FontMetrics fm = table.getFontMetrics(table.getFont());
  // Object o = table.getValueAt(row, col);
  // int w = fm.stringWidth(o.toString()) + 16 + 2 + 2;
  // Rectangle rect = table.getCellRect(row, col, true);
  // rect.setSize(w, rect.height);
  // return rect;
}
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、0列目のNameカラムのセル中にあるアイコンと文字列の上でクリックされた場合のみ、そのセルが選択されるよう設定しています。

  • JTable.putClientProperty("Table.isFileList", Boolean.TRUE)で、0列目の文字列以外がクリックされても選択されないように変更
    • WindowsLookAndFeelのみ?

参考リンク

コメント