TITLE:JTableのセルをエクスプローラ風に表示する

JTableのセルをエクスプローラ風に表示する

編集者:Terai Atsuhiro
作成日:2006-07-18
更新日:2024-02-14 (水) 23:39:51

概要

セルの中にアイコンと文字列を配置し、エクスプローラ風に見えるよう、文字列だけにフォーカスをかけます。

#screenshot

サンプルコード

public TestRenderer(JTable table) {
  super(BoxLayout.X_AXIS);
  nicon = new ImageIcon(getClass().getResource("wi0063-16.png"));
  FilteredImageSource fis = new FilteredImageSource(
                nicon.getImage().getSource(),
                new SelectedImageFilter());
  sicon = new ImageIcon(createImage(fis));
  iconLabel.setIcon(nicon);
  textLabel = new MyLabel(table);
  table.setRowHeight(textLabel.getPreferredSize().height);
}
public Component getTableCellRendererComponent(
                 JTable table, Object value, boolean isSelected,
                 boolean hasFocus, int row, int column) {
  textLabel.setText((value ==null) ? "" : value.toString());
  FontMetrics fm = table.getFontMetrics(table.getFont());
  int swidth = fm.stringWidth(textLabel.getText()) +
               textLabel.getInsets().left +
               textLabel.getInsets().right;
  int cwidth = table.getColumnModel().getColumn(column).getWidth() -
               iconLabel.getPreferredSize().width;
  textLabel.setPreferredSize(
    new Dimension((swidth>cwidth)?cwidth:swidth, 10000));
  textLabel.setSelected(isSelected);
  textLabel.setFocusedBorder(hasFocus);
  textLabel.setFont(table.getFont());
  iconLabel.setIcon((isSelected)?sicon:nicon);
  removeAll();
  add(iconLabel);
  add(textLabel);
  add(Box.createHorizontalGlue());
  return this;
}
  • &jnlp;
  • &jar;
  • &zip;

解説

エクスプローラの詳細のように表示するために、以下のような設定をしています。

  • セル間の罫線を非表示(JTable#setShowHorizontalLines, JTable#setShowVerticalLines)
  • ひとつのセルの中でアイコンと文字列を表示するセルレンダラーを作成

このレンダラーでは、アイコンと文字列を別々のJLabelで作成して並べることで、フォーカスはセルではなく文字列だけに点線で掛かるようになっています。

選択時にはセル全体の背景色を変更するのではなく、文字列を表示しているJLabelの背景色を変更し、そのPreferredSizeを文字列の長さまで縮小して右側に余白を作成しています。

  • エクスプローラ風になっていない点
    • アイコンと文字列以外の場所(セル内)をクリックしても、選択できてしまう
      • JTableで文字列をクリックした場合だけセルを選択状態にする
      • WindowsLaFでのJFileChooserはどうやっているのだろうか?
    • マウスによる範囲指定で選択することができない
    • ソートすると選択状態がクリアされてしまう
    • タブキー、矢印キーによる選択状態の移動がおかしい

参考リンク

コメント