TableColumnの幅を比率で設定

編集者:Terai Atsuhiro~

作成日:2005-11-28
更新日:2021-11-27 (土) 13:30:44
  • category: swing folder: HeaderRatio title: TableColumnの幅を比率で設定 tags: [JTable, JTableHeader, TableColumn, JScrollPane] author: aterai pubdate: 2005-11-28T18:26:47+09:00 description: 列幅調整がデフォルトのJTableで、ヘッダの各TableColumnが指定した比率の幅になるように設定します。 image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TSs6oj80RcI/AAAAAAAAAxs/hm2gp4ELiDI/s800/HeaderRatio.png

概要

列幅調整がデフォルトのJTableで、ヘッダの各TableColumnが指定した比率の幅になるように設定します。

概要

TableColumnの幅を比率で設定します。
http://terai.xrea.jp/swing/headerratio/screenshot.png

サンプルコード

#spanend
#spanadd
private void setTableHeaderColumnRaito() {
#spanend
  TableColumnModel m = table.getColumnModel();
  List<Integer> list = getWidthRaitoArray();
  int total = table.getSize().width;
  double raito = total / (double) getRaitoTotal(list);
  for (int i = 0; i < m.getColumnCount() - 1; i++) {
    TableColumn col = m.getColumn(i);
    int colwidth = (int) (.5 + list.get(i) * raito);
    col.setPreferredWidth(colwidth);
    total -= colwidth;
  }
  // 最後のカラムで余りを解消
  m.getColumn(m.getColumnCount() - 1).setPreferredWidth(total);
  table.revalidate();
#spanadd
}
#spanend
#spanadd
View in GitHub: Java, Kotlin

サンプルコード

TableColumn col0 = table.getColumnModel().getColumn(0);
TableColumn col1 = table.getColumnModel().getColumn(1);
TableColumn col2 = table.getColumnModel().getColumn(2);
int w = table.getBounds(null).width;
if(w==0) w = 512;
int wr = list[0]+list[1]+list[2];
col0.setMaxWidth(list[0]*w/wr);
col1.setMaxWidth(list[1]*w/wr);
col2.setMaxWidth(list[2]*w/wr);
table.revalidate();

解説

上記のサンプルでは、JTextFieldにコロン区切りで入力した比率に従って各カラムヘッダの幅を調整しています。
  • サンプルを起動
  • jarファイル
  • ソース
  • ComponentListener#componentResized(...)がチェックされている場合:
    • JScrollPaneに追加したComponentListenerでリサイズが実行されると全ての列幅を設定し直すのでフレームのサイズを変更してもカラムの比率は保持される
  • ComponentListener#componentResized(...)がチェックされていない場合:
    • 列幅調整がAUTO_RESIZE_SUBSEQUENT_COLUMNS(デフォルト)なので、フレームをリサイズするとその幅の変更(デルタ)がリサイズ可能なすべての列に分散して加算減算される
      • このため入力されている比率とは異なる列幅になる
    • TableColumn#setMaxWidthメソッドでカラムの幅を指定する場合、マウスのドラッグによるリサイズは不可

解説

上記のサンプルでは、カンマ区切りで入力した比率にヘッダカラムの幅を調整するようになっています。

参考リンク

JTable#setAutoResizeMode(JTable.AUTO_RESIZE_OFF)で、フレームサイズ固定なので、カラムの幅の指定にはTableColumn#setMaxWidthメソッドを使用しています。

コメント

コメント