TITLE:JTableで行を選択

JTableで行を選択

編集者:Terai Atsuhiro
作成日:2004-05-24
更新日:2021-02-07 (日) 14:54:45

概要

JTableで、行を選択した場合の動作をテストします。

#screenshot

サンプルコード

 JTable t = table;
 t.setRowSelectionAllowed(true);
 t.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
 t.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
   public void valueChanged(ListSelectionEvent e) {
     if(e.getValueIsAdjusting()) return;
     String str = "";
     if(t.getSelectedRowCount()==1) {
       str = getInfo(sorter.modelIndex(t.getSelectedRow()));
     }
     changeInfoPanel(str);
   }
 });
 private String getInfo(int index) {
   String name = (String)model.getValueAt(index, 1);
   String comment = (String)model.getValueAt(index, 2);
   return name+"( "+comment+" )";
 }
  • &jnlp;
  • &jar;
  • &zip;

解説

マウスやカーソルキー、タブキーでの選択状態の変更に対応する場合は、JTableにMouseListenerリスナーを設定するのではなく、JTable#getSelectionModelメソッドでListSelectionModelを参照し、このモデルにListSelectionListenerリスナーを追加して利用します。

ListSelectionEvent#getValueIsAdjusting()メソッドでイベントが重複処理を起こさないように制御しています。

コメント