Swing/AutoWrapTableCell のバックアップ(No.9)
- バックアップ一覧
 - 差分 を表示
 - 現在との差分 を表示
 - 現在との差分 - Visual を表示
 - ソース を表示
 - Swing/AutoWrapTableCell へ行く。
  
- 1 (2010-10-25 (月) 14:24:03)
 - 2 (2010-10-27 (水) 14:02:02)
 - 3 (2010-11-02 (火) 20:23:55)
 - 4 (2010-12-12 (日) 23:22:36)
 - 5 (2012-12-26 (水) 06:31:27)
 - 6 (2013-05-21 (火) 04:18:52)
 - 7 (2013-05-21 (火) 17:46:04)
 - 8 (2014-02-13 (木) 11:02:37)
 - 9 (2014-10-25 (土) 23:53:36)
 - 10 (2014-11-13 (木) 18:07:02)
 - 11 (2015-01-13 (火) 11:23:01)
 - 12 (2015-03-09 (月) 10:14:45)
 - 13 (2017-01-25 (水) 19:01:39)
 - 14 (2017-06-29 (木) 16:53:53)
 - 15 (2017-11-02 (木) 15:32:16)
 - 16 (2018-02-24 (土) 19:51:30)
 - 17 (2018-07-01 (日) 00:27:40)
 - 18 (2018-08-13 (月) 16:39:05)
 - 19 (2018-08-13 (月) 17:40:32)
 - 20 (2019-08-08 (木) 18:56:04)
 - 21 (2021-04-07 (水) 11:09:40)
 - 22 (2025-01-03 (金) 08:57:02)
 - 23 (2025-01-03 (金) 09:01:23)
 - 24 (2025-01-03 (金) 09:02:38)
 - 25 (2025-01-03 (金) 09:03:21)
 - 26 (2025-01-03 (金) 09:04:02)
 - 27 (2025-06-19 (木) 12:41:37)
 - 28 (2025-06-19 (木) 12:43:47)
 
 
- title: JTableのセルの高さを自動調整 tags: [JTable, JTextArea, TableCellRenderer] author: aterai pubdate: 2010-10-25T14:24:03+09:00 description: JTableのセルの高さを、文字列の折り返しに応じて自動調整します。
 
概要
JTableのセルの高さを、文字列の折り返しに応じて自動調整します。
Screenshot

Advertisement
サンプルコード
private List<List<Integer>> rowColHeight = new ArrayList<>();
private void adjustRowHeight(JTable table, int row, int column) {
  //int cWidth = table.getTableHeader().getColumnModel().getColumn(column).getWidth();
  int cWidth = table.getCellRect(row, column, false).width; //セルの内余白は含めない
  //setSize(new Dimension(cWidth, 1000)); //注目
  setBounds(table.getCellRect(row, column, false)); //もしくは?
  //doLayout();
  int prefH = getPreferredSize().height;
  while(rowColHeight.size() <= row) {
    rowColHeight.add(new ArrayList<Integer>(column));
  }
  List<Integer> colHeights = rowColHeight.get(row);
  while(colHeights.size() <= column) {
    colHeights.add(0);
  }
  colHeights.set(column, prefH);
  int maxH = prefH;
  for(Integer colHeight : colHeights) {
    if(colHeight > maxH) {
      maxH = colHeight;
    }
  }
  if(table.getRowHeight(row) != maxH) {
    table.setRowHeight(row, maxH);
  }
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、セルレンダラーに、setLineWrap(true)としたJTextAreaを使用し、カラムサイズの変更などがあったときに、そのJTextAreaの高さを取得してJTable#setRowHeight(int)メソッドで各行の高さとして設定しています。