Swing/HeaderRatio のバックアップの現在との差分(No.6)
TableColumnの幅を比率で設定
編集者:Terai Atsuhiro~
作成日:2005-11-28
更新日:2021-11-27 (土) 13:30:44
概要
列幅調整がデフォルトのJTable
で、ヘッダの各TableColumn
が指定した比率の幅になるように設定します。
Screenshot
Advertisement
概要
TableColumnの幅を比率で設定します。サンプルコード
#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#screenshot
解説
上記のサンプルでは、JTextField
にコロン区切りで入力した比率に従って各カラムヘッダの幅を調整しています。
サンプルコード
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();
-
ComponentListener#componentResized(...)
がチェックされている場合:-
JScrollPane
に追加したComponentListener
でリサイズが実行されると全ての列幅を設定し直すのでフレームのサイズを変更してもカラムの比率は保持される
-
-
ComponentListener#componentResized(...)
がチェックされていない場合:- 列幅調整が
AUTO_RESIZE_SUBSEQUENT_COLUMNS
(デフォルト)なので、フレームをリサイズするとその幅の変更(デルタ)がリサイズ可能なすべての列に分散して加算減算される- このため入力されている比率とは異なる列幅になる
-
TableColumn#setMaxWidth
メソッドでカラムの幅を指定する場合、マウスのドラッグによるリサイズは不可
- 列幅調整が
- &jnlp;
- &jar;
- &zip;