TITLE:JTableの行を移動

JTableの行を移動

編集者:Terai Atsuhiro
作成日:2004-02-23
更新日:2021-08-12 (木) 14:12:29

概要

ツールバーや、ポップアップメニューを使って、JTableの行を上下に移動します。

#screenshot

サンプルコード

 class DownAction extends AbstractAction{
   public DownAction(String str) {
     super(str);
   }
   public void actionPerformed(ActionEvent evt) {
     downActionPerformed(evt);
   }
 }
 private void downActionPerformed(ActionEvent e) {
   System.out.println("-------- 下へ --------");
   int[] pos = table.getSelectedRows();
   if(pos==null || pos.length<=0) return;
   DefaultTableModel mdl = (DefaultTableModel) table.getModel();
   if((e.getModifiers() & ActionEvent.SHIFT_MASK)!=0) {
     mdl.moveRow(pos[0], pos[pos.length-1], mdl.getRowCount()-pos.length);
     table.setRowSelectionInterval(mdl.getRowCount()-pos.length,
       mdl.getRowCount()-1);
   }else{
     if(pos[pos.length-1]==mdl.getRowCount()-1) return;
     mdl.moveRow(pos[0], pos[pos.length-1], pos[0]+1);
     table.setRowSelectionInterval(pos[0]+1, pos[pos.length-1]+1);
   }
   scrollSelectedRow();
 }
 
 public void showRowPop(MouseEvent e) {
   int row     = table.rowAtPoint(e.getPoint());
   int count   = table.getSelectedRowCount();
   int[] ilist = table.getSelectedRows();
   boolean flg = true;
   for(int i=0;i<ilist.length;i++) {
     if(ilist[i]==row) {
       flg = false;
       break;
     }
   }
   if(row>0 && flg) table.setRowSelectionInterval(row, row);
   JPopupMenu pop = new JPopupMenu();
   Action act = new TestCreateAction("追加", null);
   act.setEnabled(count>1?false:true);
   pop.add(act);
   pop.addSeparator();
   act = new DeleteAction("削除", null);
   act.setEnabled(row<0?false:true);
   pop.add(act);
   pop.addSeparator();
   act = new UpAction("上へ");
   act.setEnabled(count>0?true:false);
   pop.add(act);
   act = new DownAction("下へ");
   act.setEnabled(count>0?true:false);
   pop.add(act);
   pop.show((JComponent)e.getSource(), e.getX(), e.getY());
 }
  • &jnlp;
  • &jar;
  • &zip;

解説

上記のサンプルでは、DefaultTableModel#moveRowメソッドを使用して、選択した行を上下に動かしています。シフトキーを押しながら、ツールバーの移動ボタンを押すとそれぞれ、先頭、末尾に移動します。

コメント